5
votes

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
So to clarify, you're able to validate the JWT on the API side (presumably with [Authorize] attributes on your controller, but you want to know how to read and use the token on the frontend part of your application?UpQuark
@CamiloTerevinto edited to fix, just a slip-up.UpQuark
If I understand you correctly, you have a front-end application and a separated back-end application, so this is not a simple problem. The backend application will need to generate and validate JWTs, but does the front-end application call the back-end one from ASP.NET Core or from JavaScript?Camilo Terevinto
@UpQuark Yes exactly, I want to know how to read and use token on front-end application.JustAProgrammer
@CamiloTerevinto Your understanding is correct. I have separate back-end API and front-end application. I want to call Authenticate API on login button click and get token from API. I want to call back-end from ASP.Net Core.JustAProgrammer

1 Answers

0
votes

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