在 .NET Web API 中实现 JWT 认证需先安装必要包,再配置 JWT 参数,接着创建令牌生成服务,然后在 Program.cs 中添加认证中间件,最后通过 [Authorize] 保护接口并返回 Token。

在 .NET Web API 中实现 JWT(JSON Web Token)用户认证,主要涉及生成令牌、配置认证中间件以及保护 API 资源。下面是一个简洁实用的实现流程。
确保项目中安装了以下 NuGet 包:
可通过 NuGet 包管理器或命令行安装:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
在 appsettings.json 中添加 JWT 相关配置:
{
"JwtSettings": {
"Key": "your-very-secret-key-that-is-at-least-32-characters-long",
"Issuer": "your-api-site.com",
"Audience": "your-client-site.com",
"TokenExpirationInMinutes": 60
}
}创建一个对应的 C# 类来读取这些设置:
public class JwtSettings
{
public string Key { get; set; }
public string Issuer { get; set; }
public string Audience { get; set; }
public int TokenExpirationInMinutes { get; set; }
}在 Program.cs 中注册该配置:
builder.Configuration.GetSection("JwtSettings").Bind(new JwtSettings());
builder.Services.Configure<JwtSettings>(builder.Configuration.GetSection("JwtSettings"));创建一个服务用于生成令牌,例如:
public class TokenService
{
private readonly JwtSettings _jwtSettings;
<pre class='brush:php;toolbar:false;'>public TokenService(IOptions<JwtSettings> jwtSettings)
{
_jwtSettings = jwtSettings.Value;
}
public string GenerateToken(string userId, string role)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.Key));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, userId),
new Claim(ClaimTypes.Role, role),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token = new JwtSecurityToken(
issuer: _jwtSettings.Issuer,
audience: _jwtSettings.Audience,
claims: claims,
expires: DateTime.Now.AddMinutes(_jwtSettings.TokenExpirationInMinutes),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}}
将服务注册到依赖注入:
builder.Services.AddScoped<TokenService>();
在 Program.cs 中启用 JWT Bearer 认证:
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["JwtSettings:Issuer"],
ValidAudience = builder.Configuration["JwtSettings:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JwtSettings:Key"]))
};
});
<p>// 启用认证和授权中间件
app.UseAuthentication();
app.UseAuthorization();示例登录控制器:
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
private readonly TokenService _tokenService;
<pre class='brush:php;toolbar:false;'>public AuthController(TokenService tokenService)
{
_tokenService = tokenService;
}
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel model)
{
// 这里应验证用户名密码(可对接数据库或 Identity)
if (model.Username == "admin" && model.Password == "password")
{
var token = _tokenService.GenerateToken("1", "Admin");
return Ok(new { Token = token });
}
return Unauthorized();
}}
使用 [Authorize] 特性保护需要认证的接口:
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class SecureController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok(new { Message = "This is a secure endpoint.", User = User.Identity.Name });
}
<pre class='brush:php;toolbar:false;'>[HttpGet("admin")]
[Authorize(Roles = "Admin")]
public IActionResult AdminOnly()
{
return Ok(new { Message = "Only admins can see this." });
}}
客户端在请求时需在 Header 中携带 Token:
Authorization: Bearer <your-jwt-token>
基本上就这些。只要配置正确,.NET 的 JWT 支持非常稳定且易于扩展。注意密钥安全、过期时间合理设置,并结合 HTTPS 使用。
以上就是.NET Web API如何实现JWT用户认证的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号