当前位置:首页 > C# > 正文

ASP.NET Core JWT身份验证实战(手把手教你自定义JWT声明)

在现代Web开发中,ASP.NET Core JWT 已成为构建安全API的主流方案。JWT(JSON Web Token)不仅轻量、无状态,还支持丰富的自定义信息——也就是我们常说的“声明(Claims)”。本文将从零开始,带你一步步实现自定义JWT声明,即使你是C#初学者也能轻松上手!

ASP.NET Core JWT身份验证实战(手把手教你自定义JWT声明) JWT 自定义JWT声明 C# JWT认证 Web API安全 第1张

什么是JWT声明(Claims)?

JWT由三部分组成:Header(头部)、Payload(载荷)和Signature(签名)。其中,Payload部分包含的就是各种声明(Claims)。标准声明如 sub(主题)、exp(过期时间)等,但我们也可以添加自己的业务数据,比如用户角色、部门ID、手机号等。

第一步:创建ASP.NET Core Web API项目

打开Visual Studio或使用命令行创建一个新项目:

dotnet new webapi -n JwtCustomClaimsDemocd JwtCustomClaimsDemo

第二步:安装JWT相关NuGet包

在项目根目录运行以下命令:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

第三步:配置JWT认证服务

打开 Program.cs(.NET 6+)文件,添加JWT认证配置:

using Microsoft.IdentityModel.Tokens;using System.Text;var builder = WebApplication.CreateBuilder(args);// 添加JWT认证服务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"]!))    };});builder.Services.AddControllers();var app = builder.Build();app.UseAuthentication();app.UseAuthorization();app.MapControllers();app.Run();

第四步:在appsettings.json中配置密钥

appsettings.json 中添加JWT配置:

{  "Jwt": {    "Key": "YourVerySecureSecretKey123!",    "Issuer": "https://yourdomain.com",    "Audience": "https://yourclient.com"  }}

第五步:创建登录接口并生成带自定义声明的Token

新建一个控制器 AuthController.cs

using Microsoft.AspNetCore.Mvc;using Microsoft.IdentityModel.Tokens;using System.IdentityModel.Tokens.Jwt;using System.Security.Claims;using System.Text;[ApiController][Route("[controller]")]public class AuthController : ControllerBase{    private readonly IConfiguration _config;    public AuthController(IConfiguration config)    {        _config = config;    }    [HttpPost("login")]    public IActionResult Login([FromBody] LoginModel model)    {        // 这里应验证用户名密码(为简化省略数据库查询)        if (model.Username == "admin" && model.Password == "123456")        {            var claims = new List<Claim>            {                new Claim(ClaimTypes.Name, model.Username),                new Claim(ClaimTypes.Role, "Admin"),                // 👇 自定义声明:部门ID                new Claim("DepartmentId", "101"),                // 👇 自定义声明:手机号                new Claim("PhoneNumber", "13800138000")            };            var key = new SymmetricSecurityKey(                Encoding.UTF8.GetBytes(_config["Jwt:Key"]!));            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);            var token = new JwtSecurityToken(                issuer: _config["Jwt:Issuer"],                audience: _config["Jwt:Audience"],                claims: claims,                expires: DateTime.Now.AddHours(2),                signingCredentials: creds);            return Ok(new            {                token = new JwtSecurityTokenHandler().WriteToken(token)            });        }        return Unauthorized();    }}public class LoginModel{    public string Username { get; set; } = string.Empty;    public string Password { get; set; } = string.Empty;}

第六步:在受保护的API中读取自定义声明

现在你可以在任何需要授权的控制器中获取这些自定义声明:

[ApiController][Route("[controller]")][Authorize]public class UserController : ControllerBase{    [HttpGet("profile")]    public IActionResult GetProfile()    {        var departmentId = User.FindFirst("DepartmentId")?.Value;        var phoneNumber = User.FindFirst("PhoneNumber")?.Value;        return Ok(new        {            UserName = User.Identity?.Name,            DepartmentId = departmentId,            PhoneNumber = phoneNumber        });    }}

总结

通过以上步骤,你已经成功实现了在 ASP.NET Core JWT 中添加和使用自定义JWT声明。这种机制非常适合传递用户上下文信息,避免频繁查询数据库。记住,敏感信息(如密码)绝不能放入JWT中!

掌握这项技能后,你的 C# JWT认证 能力将大幅提升,为构建更安全、高效的 Web API安全 架构打下坚实基础。

提示:生产环境中请使用强密钥,并考虑使用证书或Azure Key Vault管理密钥。