首先生成JWT Token并在中间件中配置验证,最后用[Authorize]保护API;JWT由Header、Payload、Signature组成,具有无状态、可跨域优点;C#中通过JwtSecurityTokenHandler生成Token,使用AddJwtBearer配置认证,确保密钥安全与Token有效期管理。

JWT(jsON Web Token)是一种开放标准(RFC 7519),用于在各方之间安全地传输信息作为json对象。C#中使用JWT认证,通常用于Web API的身份验证,确保请求来自合法用户。
在ASP.NET Core Web API中实现JWT验证,主要分为三步:生成Token、配置认证中间件、保护API端点。下面详细介绍如何操作。
什么是JWT?
JWT由三部分组成:Header(头部)、Payload(载荷)和Signature(签名)。它通常以字符串形式表示,如:
eyJhbGciOiJIUzI1NiisInR5cCI6IkpXVCJ9.xxxxxx.xxxxxx
JWT的优点包括无状态、可跨域、自包含。服务器不需要存储会话信息,适合分布式系统。
如何生成JWT Token
在用户登录成功后,服务器生成Token并返回给客户端。以下是一个生成Token的示例代码:
1. 安装NuGet包:
microsoft.AspNetCore.Authentication.JwtBearer
2. 创建Token生成方法:
// 示例:使用HmacSHA256加密
var key = Encoding.ASCII.GetBytes(“your-secret-key-here-32-Chars-min”);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, “user123”)
}),
Expires = DateTime.UtcNow.AddHours(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
将tokenString返回给前端,后续请求需在Authorization头中携带:Bearer {token}
配置JWT认证中间件
在Program.cs或Startup.cs中配置JWT验证服务:
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(“your-secret-key-here-32-chars-min”))
};
});
// 启用认证和授权中间件
app.UseAuthentication();
app.UseAuthorization();
注意:密钥长度建议至少32字符,生产环境应从配置文件读取,不要硬编码。
保护API接口
在需要验证的控制器或方法上添加[Authorize]特性:
[Authorize]
[ApiController]
[Route(“api/[controller]”)]
public class SecureController : ControllerBase
{
[HttpGet]
public IActionResult GetData()
{
return Ok(“这是受保护的数据”);
}
}
未携带有效Token的请求将返回401 Unauthorized。
基本上就这些。只要正确生成Token并在中间件中配置验证逻辑,就能实现安全的JWT认证。关键点是密钥管理、Token有效期控制和防止重放攻击。实际项目中可结合刷新Token机制提升安全性。