JwtAdapter 1.1.15

dotnet add package JwtAdapter --version 1.1.15
                    
NuGet\Install-Package JwtAdapter -Version 1.1.15
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="JwtAdapter" Version="1.1.15" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="JwtAdapter" Version="1.1.15" />
                    
Directory.Packages.props
<PackageReference Include="JwtAdapter" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add JwtAdapter --version 1.1.15
                    
#r "nuget: JwtAdapter, 1.1.15"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#addin nuget:?package=JwtAdapter&version=1.1.15
                    
Install JwtAdapter as a Cake Addin
#tool nuget:?package=JwtAdapter&version=1.1.15
                    
Install JwtAdapter as a Cake Tool

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

  1. 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"
        };
    });
  1. 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; }
}
  1. 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
);
  1. 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

  1. Fork the repository.
  2. Create a new branch.
  3. Make your changes.
  4. Commit your changes.
  5. Push your changes to your fork.
  6. 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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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 Downloads Last updated
1.1.15 190 3/10/2025
1.1.14 110 2/27/2025
1.1.13 103 2/1/2025
1.1.12 102 2/1/2025
1.1.11 104 1/5/2025
1.1.1 125 1/3/2025
1.1.0 124 1/3/2025
1.0.0 122 1/3/2025

Version 1.1.15 - Updated validation function,Added method for hashing and comparing password