JwtAdapter 1.1.15
dotnet add package JwtAdapter --version 1.1.15
NuGet\Install-Package JwtAdapter -Version 1.1.15
<PackageReference Include="JwtAdapter" Version="1.1.15" />
<PackageVersion Include="JwtAdapter" Version="1.1.15" />
<PackageReference Include="JwtAdapter" />
paket add JwtAdapter --version 1.1.15
#r "nuget: JwtAdapter, 1.1.15"
#addin nuget:?package=JwtAdapter&version=1.1.15
#tool nuget:?package=JwtAdapter&version=1.1.15
JwtAdapter
Overview
JwtAdapter is a lightweight and flexible SDK designed to simplify enabling and managing JWT-based authentication in .NET APIs. It provides an easy-to-use extension method for configuring JWT authentication, including custom validation logic and dynamic claim injection.
Features
• Simple Configuration: Quickly enable JWT authentication using a single extension method.
• Custom Validation: Inject custom validation logic to tailor authentication to your needs.
• Dynamic Claims: Add dynamic claims based on validation results.
• Lifetime Validation: Optionally validate token expiration automatically.
Installation
To install JwtAdapter, simply add the NuGet package to your project using the following command:
dotnet add package JwtAdapter
Getting Started
- Define BearerTokenConfig
Define the JWT configuration, such as the issuer, audience, and signing key
services.EnableAuthentication<UserIdentity>(
config =>
{
config.Issuer = "YourIssuer";
config.Audience = "YourAudience";
config.SigningKey = "YourSigningKey";
},
async id =>
{
// Example validation logic
if (id == "valid-user-id")
{
return new IdentityValidationResults<UserIdentity>
{
IsSuccessful = true,
Message = "Validation succeeded",
IdentityData = new UserIdentity { Id = id, Name = "John Doe" }
};
}
return new IdentityValidationResults<UserIdentity>
{
IsSuccessful = false,
Message = "Invalid user"
};
});
- Define Custom Validation Logic
The validationFunction takes a user ID and returns an IdentityValidationResults<T> object containing:
- IsSuccessful: A boolean indicating validation success.
- Message: A message explaining the validation result.
- IdentityData: Optional data to attach as claims.
Example IdentityValidationResults class:
public class IdentityValidationResults<T>
{
public bool IsSuccessful { get; set; }
public string? Message { get; set; }
public T? IdentityData { get; set; }
}
- Add Claims Dynamically
Claims are added to the authenticated user’s identity dynamically during validation. The following example adds a serialized IdentityData and the token itself as claims:
var claims = new List<Claim>
{
new Claim(ClaimTypes.Thumbprint, results.IdentityData?.ToJsonString() ?? string.Empty),
new Claim(ClaimTypes.Authentication, bearerAuth)
};
Advanced Configuration
Lifetime Validation
By default, JwtAdapter does not validate token expiration. To enable lifetime validation, set the ValidateLifetime property to true in the BearerTokenConfig object.
services.EnableAuthentication<UserIdentity>(
config =>
{
config.Issuer = "YourIssuer";
config.Audience = "YourAudience";
config.SigningKey = "YourSigningKey";
},
validationFunction,
validateLifeTime: false
);
- Hash and Compare Passwords
//hash password
var rawPassword="password";
var hashedPassword=rawPassword.HashPassword();
//compare password
var isMatch=rawPassword.ComparePassword(hashedPassword);
Custom Error Messages
Provide detailed error messages when validation fails:
return new IdentityValidationResults<UserIdentity>
{
IsSuccessful = false,
Message = "User is not authorized to access this resource."
};
Example Usage
Startup.cs or Program.cs Configuration
//Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.EnableAuthentication<UserIdentity>(
config =>
{
config.Issuer = "MyIssuer";
config.Audience = "MyAudience";
config.SigningKey = "MySecretKey";
},
async (id,claims) =>
{
// Perform custom validation
return await ValidateUserAsync(id);
}
);
}
//Program.cs
var builder = WebApplication.CreateBuilder(args);
{
var services = builder.Services;
var config = builder.Configuration;
services.EnableAuthentication<UserIdentity>(
config =>
{
config.Issuer = "MyIssuer";
config.Audience = "MyAudience";
config.SigningKey = "MySecretKey";
},
async id =>
{
// Perform custom validation
return await ValidateUserAsync(id);
}
);
}
Enable Authentication and Authorization Middleware
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization(); // the UseAuthorization Middleware must come between the UseRouring and UseEndpoints Middleware
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Add BearTokenConfig to appsettings
{
"BearerTokenConfig": {
"Issuer": "https://easecoreapi:com",
"Audience": "https://easycoreapi:com",
"SigningKey": "easycoreapi889945"
}
}
Controller Usage
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class SecureController : ControllerBase
{
[HttpGet("protected")]
public IActionResult GetProtectedData()
{
return Ok("This is protected data.");
}
}
Requirements
- .NET 6.0 or .Net 8.0
- Compatible with ASP.NET Core applications.
Contributing
- Fork the repository.
- Create a new branch.
- Make your changes.
- Commit your changes.
- Push your changes to your fork.
- Submit a pull request.
License
This project is licensed under the MIT License.
Support
For any questions or issues, please open an issue on GitHub or contact us at <a href="mailto:developer.biliksuun@gmail.com"> developer.biliksuun@gmail.com</a>.
Authors
- Samuel Biliksuun
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. |
-
net6.0
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 6.0.10)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 7.0.0)
- Microsoft.Extensions.Options (>= 7.0.0)
- Newtonsoft.Json (>= 13.0.3)
- Scrypt.NET (>= 1.3.0)
- System.IdentityModel.Tokens.Jwt (>= 7.2.0)
-
net8.0
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 6.0.10)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 7.0.0)
- Microsoft.Extensions.Options (>= 7.0.0)
- Newtonsoft.Json (>= 13.0.3)
- Scrypt.NET (>= 1.3.0)
- System.IdentityModel.Tokens.Jwt (>= 7.2.0)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on JwtAdapter:
Package | Downloads |
---|---|
DotNetApiMongoDbTemplateV8
DotnetApiMongoDbTemplateV8 is a comprehensive, ready-to-use template for building modern .NET APIs with MongoDB. Designed to simplify and accelerate API development, this template integrates essential tools and follows best practices, making it ideal for developers looking for a solid foundation for their projects. |
GitHub repositories
This package is not used by any popular GitHub repositories.
Version 1.1.15 - Updated validation function,Added method for hashing and comparing password