可以在令牌中添加自定义声明,例如角色信息,并使用中间件将其提取到HttpContext.User中,以便在应用程序中的任何位置轻松访问它。
首先,在令牌中添加角色信息的示例代码如下:
var claims = new List
var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) };
接下来,在Startup.cs文件中的ConfigureServices方法中配置JwtBearerOptions,以便将令牌中的角色信息添加到HttpContext.User中:
services.AddAuthentication(token => { token.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; token.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false }; options.Events = new JwtBearerEvents { OnTokenValidated = context => { if (context.Principal.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Role) != null) { var roles = context.Principal.FindAll(ClaimTypes.Role).Select(x => x.Value).ToList(); // 将角色信息添加到HttpContext.User中并准备在应用程序中使用 var claimsIdentity = context.Principal.Identity as ClaimsIdentity; claimsIdentity.AddClaims(roles.Select(r => new Claim