ASP.NET Core 2.2 JWT Authentication

帅比萌擦擦* 提交于 2019-12-22 06:51:09

问题


I've been learning about ASP.NET Core 2.2 recently and trying to develop a Role-Based login sample(Website + Web API) using JWT token.

Definition is simple:

  • if user's role is "admin" then it redirects to admin page.
  • if user's role is "user" then it redirects to user page.

But most of the solutions and articles I found on "JWT token with ASP.NET Core 2.2" is only for Web API.

I've almost understood how JWT token works and how to implement it on Web API side from following article :

http://jasonwatmore.com/post/2019/01/08/aspnet-core-22-role-based-authorization-tutorial-with-example-api

Now my problem is how to consume above API using ASP.NET Core Website?

This might be a simple problem for many a guys but I'm fairly new to web development and don't understand a lot of things.

Any help would be appreciated. Thanks in advance.


回答1:


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(){ }


来源:https://stackoverflow.com/questions/55699789/asp-net-core-2-2-jwt-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!