在C# .NET Core Web应用中配置JWT(JSON Web Token)可以实现安全的身份验证和授权机制。通常涉及以下几个步骤:
安装必要的NuGet包
确保项目中安装了以下NuGet包:
Microsoft.AspNetCore.Authentication.JwtBearer
Microsoft.IdentityModel.Tokens
可以通过NuGet包管理器或命令行安装:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package Microsoft.IdentityModel.Tokens
配置 JWT 参数(appsettings.json)
在 appsettings.json 中添加 JWT 配置:
{
"Jwt": {
"Key": "YourSuperSecretKeyHere_至少16位", // 密钥(推荐使用至少16位)
"Issuer": "https://yourdomain.com", // 签发者
"Audience": "https://yourdomain.com", // 接收者
"ExpireMinutes": 60 // 过期时间(分钟)
}
}
配置JWT认证
在program.cs
文件中配置JWT认证:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// 添加 JWT 认证 两种写法
//builder.Services.AddAuthentication(options =>
//{
//options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
//定义在 认证(Authentication) 时默认使用的方案(例如解析 JWT Token)。
//options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
//定义在 质询(Challenge) 时默认使用的方案(例如返回 401 Unauthorized 或跳转到登录页)。
//options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
//当未显式指定认证方案时,系统默认使用的认证方案。
//})
//简化写法是仅设置 DefaultScheme,其他两个关键属性(Authenticate 和 Challenge)未配置。
//实际使用时返回为null
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true, // 验证签发者
ValidateAudience = true, // 验证接收者
ValidateLifetime = true, // 验证过期时间
ValidateIssuerSigningKey = true, // 验证签名密钥
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!)
)
};
});
builder.Services.AddAuthorization(); // 添加授权中间件
var app = builder.Build();
app.UseAuthentication(); // 启用认证
app.UseAuthorization(); // 启用授权
app.MapControllers();
app.Run();
经过上述配置 JWT 已经基本注册在服务中了,接下来是在控制器controller中生成具体的token 用于用户的访问鉴权
生成JWT Token
在控制器或服务中生成JWT Token。包括以下步骤:
// Services/JwtService.cs
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
public class JwtService
{
private readonly IConfiguration _config;
public JwtService(IConfiguration config)
{
_config = config;
}
public string GenerateToken(string username, string role)
{
//1. 生成 JWT 时添加标准声明 JwtRegisteredClaimNames 类规定的字段有很多 感兴趣的见代码下方的link
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, "user123"),
new Claim(JwtRegisteredClaimNames.Iss, "https://your-auth-server.com"),
new Claim(JwtRegisteredClaimNames.Aud, "https://your-api.com"),
new Claim(JwtRegisteredClaimNames.Exp, DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
// 自定义声明(非标准)
new Claim("role", "admin")
};
//2. 获取之前配置的 JWT Key
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]!));
//3. 指定签名算法和密钥, 配置签名凭证(Signing Credentials)
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
//4. 生成 JWT Token 组合头部(Header)、载荷(Payload)和签名(Signature)。
var token = new JwtSecurityToken(
issuer: _config["Jwt:Issuer"],
audience: _config["Jwt:Audience"],
claims: claims,
expires: DateTime.Now.AddMinutes(Convert.ToDouble(_config["Jwt:ExpireMinutes"])),
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
保护API端点
使用[Authorize]
属性保护需要认证的API端点:
[Authorize]
[HttpGet("protected")]
public IActionResult Protected()
{
return Ok("This is a protected endpoint.");
}
创建登录接口(生成 Token)
// Controllers/AuthController.cs
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/auth")]
public class AuthController : ControllerBase
{
private readonly JwtService _jwtService;
public AuthController(JwtService jwtService)
{
_jwtService = jwtService;
}
[HttpPost("login")]
public IActionResult Login([FromBody] LoginRequest request)
{
// 模拟用户验证(实际应查询数据库)
if (request.Username == "admin" && request.Password == "123456")
{
var token = _jwtService.GenerateToken(request.Username, "Admin");
return Ok(new { Token = token });
}
return Unauthorized("用户名或密码错误");
}
}
public class LoginRequest
{
public string Username { get; set; }
public string Password { get; set; }
}
通过以上步骤,可以在C# .NET Core Web应用中成功配置和使用JWT进行认证和授权。
整体来说还是比较复杂的,里面的可扩展性很强,但是实际使用的配置并不是很多,基本也就是流程化的操作。