使用我在评论中发布的指南。这不是您所需要的 - 但我不能在评论中发布代码。需要长格式。
您使用声明将角色放入您的令牌中。
在你的 startup.cs
var secretKey = Configuration.GetSection("JWTSettings:SecretKey").Value;
var issuer = Configuration.GetSection("JWTSettings:Issuer").Value;
var audience = Configuration.GetSection("JWTSettings:Audience").Value;
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = issuer,
ValidateAudience = true,
ValidAudience = audience,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
};
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = tokenValidationParameters;
});
然后在用户用来“登录”或发出令牌的控制器方法中。
var claims = new[] {
new Claim(ClaimTypes.Name, Credentials.Email),
new Claim(ClaimTypes.Role, Role) };
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.SecretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _options.Issuer,
audience: _options.Audience,
claims: claims,
expires: DateTime.Now.AddYears(10),
signingCredentials: creds);
然后用角色保护你的方法或控制器。
[Authorize(Roles = "Admin")]
[HttpGet]
Public IActionResult GrabStuff(){ }