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
<PackageReference Include="Jwt.Authentication.Manager" Version="2.2.1.2" />
<PackageVersion Include="Jwt.Authentication.Manager" Version="2.2.1.2" />
<PackageReference Include="Jwt.Authentication.Manager" />
paket add Jwt.Authentication.Manager --version 2.2.1.2
#r "nuget: Jwt.Authentication.Manager, 2.2.1.2"
#addin nuget:?package=Jwt.Authentication.Manager&version=2.2.1.2
#tool nuget:?package=Jwt.Authentication.Manager&version=2.2.1.2
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:
IJwtAuthenticationManager
- Defines the contract for generating JWT tokens used in authentication and authorization.JwtAuthenticationManager
- Default implementation ofIJwtAuthenticationManager
that uses symmetric key signing to generate JWT tokens with configurable settings.JwtSettings
- Represents configuration settings used for generating and validating JWT tokens.
Below are the main methods for working with JWT:
AddJwtAuthentication()
- Adds and configures JWT authentication and authorization services for the application. Is an extension method forIServiceCollection
.GenerateToken()
- Generates a JWT string based on the provided claims.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 | Versions 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. |
-
net7.0
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 7.0.20)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 9.0.4)
- Microsoft.IdentityModel.Tokens (>= 6.36.0)
- System.IdentityModel.Tokens.Jwt (>= 6.36.0)
-
net8.0
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 7.0.20)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 9.0.4)
- Microsoft.IdentityModel.Tokens (>= 6.36.0)
- System.IdentityModel.Tokens.Jwt (>= 6.36.0)
-
net9.0
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 7.0.20)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 9.0.4)
- Microsoft.IdentityModel.Tokens (>= 6.36.0)
- System.IdentityModel.Tokens.Jwt (>= 6.36.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
update readme.md, added description of the main entities