Jwt.Authentication.Manager 2.2.1.2

dotnet add package Jwt.Authentication.Manager --version 2.2.1.2
                    
NuGet\Install-Package Jwt.Authentication.Manager -Version 2.2.1.2
                    
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="Jwt.Authentication.Manager" Version="2.2.1.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Jwt.Authentication.Manager" Version="2.2.1.2" />
                    
Directory.Packages.props
<PackageReference Include="Jwt.Authentication.Manager" />
                    
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 Jwt.Authentication.Manager --version 2.2.1.2
                    
#r "nuget: Jwt.Authentication.Manager, 2.2.1.2"
                    
#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=Jwt.Authentication.Manager&version=2.2.1.2
                    
Install Jwt.Authentication.Manager as a Cake Addin
#tool nuget:?package=Jwt.Authentication.Manager&version=2.2.1.2
                    
Install Jwt.Authentication.Manager as a Cake Tool

JWTAuthenticationManager

This library provides a reusable implementation of JWT-based authentication for ASP.NET Core applications. The goal is to avoid repeating boilerplate code across projects and simplify the setup of secure, token-based authentication. The library is intended for internal use or integration into microservices where consistent authentication logic is required.

Description

Main entities of the library:

  1. IJwtAuthenticationManager - Defines the contract for generating JWT tokens used in authentication and authorization.
  2. JwtAuthenticationManager - Default implementation of IJwtAuthenticationManager that uses symmetric key signing to generate JWT tokens with configurable settings.
  3. JwtSettings - Represents configuration settings used for generating and validating JWT tokens.

Below are the main methods for working with JWT:

  1. AddJwtAuthentication() - Adds and configures JWT authentication and authorization services for the application. Is an extension method for IServiceCollection.
  2. GenerateToken() - Generates a JWT string based on the provided claims.
  3. GetRemainingLifeTime() - Calculates the remaining lifetime, in seconds, of the specified JWT token.

Usage

Add JWT authentication in Program.cs

builder.Services.AddJwtAuthentication(
    new JwtBearerOptions
    {
        RequireHttpsMetadata = false,
        TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = false,
            ValidateAudience = false,
            ValidateLifetime = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecret)),
            ValidateIssuerSigningKey = true,
            ClockSkew = TimeSpan.Zero,
            NameClaimType = nameClaimType
        },
        Events = new JwtBearerEvents
        {
            OnTokenValidated = ctx =>
            {
                var clsOnly = ctx.Principal.Claims.Any(c => c.Type == "clsOnly" && c.Value == "true");
                var clsRequest = ClsRequests.Any(r => ctx.Request.Path.Value?.StartsWith(r) ?? false);

                if (clsOnly && !clsRequest)
                    ctx.Fail(Error.ClsOnlyError);

                return Task.CompletedTask;
            }
        }
    }, 
    new JwtSettings
    {
        SecretKey = jwtSecret,
        ExpirationInMinutes = 240
    }
);

! you don't have to write AddAuthorization(), because the AddJwtAuthentication() method already does that !

Then you can use the IJwtAuthenticationManager interface in your services and controllers from DI container:

[ApiController]
[Route("api")]   
public class AuthenticationController : ControllerBase
{
    private readonly IJwtAuthenticationManager _authManager;

    public AuthenticationController(IJwtAuthenticationManager authManager)
    {
        _authManager = authManager;
    }
}

There is some examples how you can generate tokens and get remaining token lifespan in seconds:

[HttpPost("auth")]
[AllowAnonymous]       
public async Task<IActionResult> AuthAsync([FromBody] AuthenticationDTOModel auth, CancellationToken cancellationToken)
{
    if (!ModelState.IsValid) 
        return BadRequest($"Невалидные данные для {nameof(auth)}.");

    try
    {
        var user = await _userServiсe.CheckUserAsync(auth.Login, auth.ClientTitle, auth.Password, cancellationToken);
        if (user == null) return Unauthorized();

        var token = _authManager.GenerateToken(new List<Claim>
        {
            new("userName", user.UserName),
            new("clientTitle", Convert.ToBase64String(Encoding.UTF8.GetBytes(string.IsNullOrEmpty(user.ClientTitle) ? "" : user.ClientTitle))),
            new("clientId", (user.ClientId ?? 0).ToString()),
            new("userId", user.Id.ToString()),
            new("isSuper", user.IsAdmin.ToString()),
            new("isAdmin", user.IsAdmin.ToString()),
            new("login", Convert.ToBase64String(Encoding.UTF8.GetBytes(user.UserName))),
        });

        return Ok(new { token });
    }
    catch (Exception ex)
    {
        return StatusCode(500, ex.Message);
    }
}

[Authorize]
[HttpGet("remaining-lifetime")]
public IActionResult GetRemainingTokenLifetime()
{
    _ = HttpContext.Request.Headers.TryGetValue("Authorization", out var token);

    try
    {
        var totalSeconds = _authManager.GetRemainingLifeTime(token.ToString());
        return Ok(totalSeconds);
    }
    catch (Exception)
    {
        return NotFound(Error.NoJWTInHeader);
    }
}
Product Compatible and additional computed target framework versions.
.NET net7.0 is compatible.  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 is compatible.  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.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2.2.1.2 177 5/12/2025
2.2.1.1 122 5/6/2025
2.2.1 124 5/6/2025
2.2.0 287 5/6/2025

update readme.md, added description of the main entities