首先配置JWT认证服务并添加认证授权中间件,然后生成包含用户信息的JWT令牌,接着通过[Authorize]特性保护接口,最后在appsettings.json中设置JWT参数,确保密钥安全及中间件顺序正确。

在现代 Web 应用开发中,JWT(JSON Web Token)是一种广泛使用的无状态身份验证机制。C# 结合 ASP.NET Core 可以非常方便地实现 JWT 认证与授权。下面介绍如何在 ASP.NET Core 项目中完整实现 JWT 用户登录认证和接口访问授权。
要在项目中启用 JWT 认证,首先需要在 Program.cs 或 Startup.cs 中配置认证服务。
确保安装了以下 NuGet 包:在 Program.cs 中添加认证配置:
var builder = WebApplication.CreateBuilder(args);
<p>// 添加认证服务
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["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
});</p><p>// 添加授权服务
builder.Services.AddAuthorization();</p><p>var app = builder.Build();</p><p>// 启用认证和授权中间件
app.UseAuthentication();
app.UseAuthorization();
当用户登录成功后,服务器应生成 JWT 令牌并返回给客户端。
创建一个登录接口,例如:
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
private readonly IConfiguration _configuration;
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">public AuthController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel model)
{
// 示例:简单验证用户名密码(实际应查询数据库)
if (model.Username == "admin" && model.Password == "123456")
{
var token = GenerateJwtToken(model.Username);
return Ok(new { Token = token });
}
return Unauthorized();
}
private string GenerateJwtToken(string username)
{
var securityKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, username),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.Name, username)
};
var token = new JwtSecurityToken(
issuer: _configuration["Jwt:Issuer"],
audience: _configuration["Jwt:Audience"],
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}}
通过 [Authorize] 特性可以限制只有携带有效 JWT 的请求才能访问特定接口。
示例:受保护的 API 接口
[ApiController]
[Route("api/[controller]")]
public class SecureController : ControllerBase
{
[HttpGet]
[Authorize]
public IActionResult GetSecret()
{
return Ok(new { Message = "你已通过认证", User = User.Identity.Name });
}
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">[HttpGet("admin")]
[Authorize(Roles = "Admin")]
public IActionResult GetAdminData()
{
return Ok(new { Message = "管理员专用数据" });
}}
上面的例子中,第一个接口要求用户登录即可访问,第二个接口还要求用户具有 Admin 角色。
若需支持角色,可在生成 Token 时添加角色声明:
new Claim(ClaimTypes.Role, "Admin")
在 appsettings.json 中定义 JWT 配置:
{
"Jwt": {
"Key": "your-very-secret-key-that-is-long-enough",
"Issuer": "https://localhost:5001",
"Audience": "https://localhost:5001"
}
}
密钥长度建议至少 32 字符,使用强随机字符串以保证安全。
基本上就这些。只要正确配置认证服务、生成 Token 并在请求头中携带 Bearer Token,ASP.NET Core 就能自动完成验证。前端发送请求时,记得在 Header 中加上:
Authorization: Bearer <your-jwt-token>
不复杂但容易忽略的是中间件顺序:UseAuthentication 必须在 UseAuthorization 之前。
以上就是C# 如何实现 JWT 用户认证和授权_C# JWT 认证授权实现教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号