ASP.NET Core 2.2 JWT Authentication

余生颓废 提交于 2019-12-05 10:28:04

Using the guide i posted in the comments. This isn't all you need - but i cant post code in comments. Needed long form.

You use claims to get the role into your token.

In your 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;
    });

Then in your controller method that a user uses to "login" or issue a token.

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);

Then protect your method or controller with the role.

 [Authorize(Roles = "Admin")]
   [HttpGet]
   Public IActionResult GrabStuff(){ }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!