Azrng.AspNetCore.Authentication.JwtBearer
1.4.0
dotnet add package Azrng.AspNetCore.Authentication.JwtBearer --version 1.4.0
NuGet\Install-Package Azrng.AspNetCore.Authentication.JwtBearer -Version 1.4.0
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="Azrng.AspNetCore.Authentication.JwtBearer" Version="1.4.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Azrng.AspNetCore.Authentication.JwtBearer" Version="1.4.0" />
<PackageReference Include="Azrng.AspNetCore.Authentication.JwtBearer" />
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 Azrng.AspNetCore.Authentication.JwtBearer --version 1.4.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: Azrng.AspNetCore.Authentication.JwtBearer, 1.4.0"
#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.
#:package Azrng.AspNetCore.Authentication.JwtBearer@1.4.0
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Azrng.AspNetCore.Authentication.JwtBearer&version=1.4.0
#tool nuget:?package=Azrng.AspNetCore.Authentication.JwtBearer&version=1.4.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
Azrng.AspNetCore.Authentication.JwtBearer
一个简单易用的 ASP.NET Core JWT Bearer 认证库,提供了开箱即用的配置和灵活的扩展能力。
NuGet 包
dotnet add package Azrng.AspNetCore.Authentication.JwtBearer
功能特性
- ✅ 开箱即用的 JWT Token 生成和验证
- ✅ 自动处理 Token 过期和认证失败
- ✅ 内置性能优化(缓存 SecurityKey 和 SigningCredentials)
- ✅ 完整的 Token 验证(签名、过期时间、颁发者、受众)
- ✅ 支持自定义 JwtBearerEvents(如 SignalR 支持)
- ✅ 可空引用类型支持
- ✅ 支持 .NET 6.0+
快速开始
1. 基础配置
// 在 Program.cs 或 Startup.cs 中配置服务
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearerAuthentication(options =>
{
options.JwtAudience = "your-audience";
options.JwtIssuer = "your-issuer";
options.JwtSecretKey = "your-secret-key-at-least-16-characters-long";
});
// 启用认证授权
app.UseAuthentication();
app.UseAuthorization();
2. 生成 Token
注入 IBearerAuthService 来创建 Token:
public class AuthService
{
private readonly IBearerAuthService _bearerAuthService;
public AuthService(IBearerAuthService bearerAuthService)
{
_bearerAuthService = bearerAuthService;
}
// 生成仅包含用户ID的 Token
public string GenerateToken(string userId)
{
return _bearerAuthService.CreateToken(userId);
}
// 生成包含用户ID和用户名的 Token
public string GenerateToken(string userId, string userName)
{
return _bearerAuthService.CreateToken(userId, userName);
}
// 生成自定义 Claims 的 Token
public string GenerateToken(IEnumerable<Claim> claims)
{
return _bearerAuthService.CreateToken(claims);
}
}
3. 使用 Token 验证
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
[HttpGet("profile")]
[Authorize] // 需要认证
public IActionResult GetProfile()
{
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
return Ok(new { UserId = userId });
}
}
高级用法
支持 SignalR(从查询参数读取 Token)
如果你的应用使用 SignalR,需要从查询参数中读取 Token:
services.AddAuthentication()
.AddJwtBearerAuthentication(
// JWT 配置
jwtConfig =>
{
jwtConfig.JwtAudience = "your-audience";
jwtConfig.JwtIssuer = "your-issuer";
jwtConfig.JwtSecretKey = "your-secret-key";
},
// JwtBearerEvents 自定义配置
events =>
{
// 添加 OnMessageReceived 处理器
events.OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
// 如果是 SignalR 请求且包含 access_token,则从查询参数读取
if (!string.IsNullOrEmpty(accessToken) &&
(path.StartsWithSegments("/chathub") || path.StartsWithSegments("/notificationhub")))
{
context.Token = accessToken;
}
return Task.CompletedTask;
};
});
注意:此方法会保留默认的
OnAuthenticationFailed和OnChallenge事件处理,不会覆盖它们。
自定义 Token 验证失败响应
services.AddAuthentication()
.AddJwtBearerAuthentication(
jwtConfig => { /* ... */ },
events =>
{
events.OnChallenge = context =>
{
// 自定义响应
context.HandleResponse();
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
context.Response.WriteAsJsonAsync(new
{
success = false,
message = "未授权访问",
code = 401
});
return Task.CompletedTask;
};
});
完整的配置选项
services.AddAuthentication()
.AddJwtBearerAuthentication(options =>
{
// JWT 签名密钥(最少16位)
options.JwtSecretKey = "your-very-long-secret-key";
// JWT 颁发者
options.JwtIssuer = "https://your-domain.com";
// JWT 受众
options.JwtAudience = "your-api-audience";
// Token 有效期(默认24小时)
options.ValidTime = TimeSpan.FromHours(2);
});
API 参考
IBearerAuthService
| 方法 | 说明 |
|---|---|
CreateToken(string userId) |
生成包含用户ID的 Token |
CreateToken(string userId, string userName) |
生成包含用户ID和用户名的 Token |
CreateToken(IEnumerable<Claim> claims) |
生成包含自定义 Claims 的 Token |
ValidateToken(string token) |
验证 Token 是否有效(签名、过期、颁发者、受众) |
GetJwtNameIdentifier(string jwtStr) |
从 Token 中获取用户标识 |
GetJwtInfo(string jwtStr) |
解析 Token 返回所有载荷信息 |
JwtTokenConfig
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
JwtSecretKey |
string |
默认密钥 | JWT 签名密钥(≥16位) |
JwtIssuer |
string |
"issuer" |
JWT 颁发者标识 |
JwtAudience |
string |
"audience" |
JWT 受众标识 |
ValidTime |
TimeSpan |
24小时 |
Token 有效期 |
默认行为
库内置了以下默认行为:
- Token 过期处理:过期 Token 会自动添加
Token-Expired: true响应头 - 认证失败响应:返回 JSON 格式的 401 错误
{ "isSuccess": false, "message": "您无权访问该接口,请确保已经登录", "code": "401" } - Token 验证:完整验证签名、过期时间、颁发者和受众
版本历史
1.4.0 (最新)
- 🆕 新增:支持自定义
JwtBearerEvents,可在默认配置基础上扩展 - ⚡ 优化:性能优化,缓存
SecurityKey和SigningCredentials - ✅ 优化:增强
ValidateToken方法,完整验证签名、过期时间、颁发者、受众 - 🔒 安全:添加可空引用类型支持
- 🐛 修复:
DateTime.Now改为DateTime.UtcNow
1.3.0
- 支持 .NET 10
1.2.0
- 移除不必要的依赖包
1.1.0
- 适配 Common.Core 1.2.1 的修改
1.0.0
- 从包 Common.JwtToken 中迁移过来
许可证
版权归 Azrng 所有
| 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 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 is compatible. 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.
-
net10.0
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 10.0.0)
-
net6.0
-
net7.0
-
net8.0
-
net9.0
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.