5

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.

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
vishwas-trivedi
  • 516
  • 2
  • 8
  • 26
  • 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 Apr 16 '19 at 02:46
  • @CamiloTerevinto edited to fix, just a slip-up. – UpQuark Apr 16 '19 at 02:48
  • 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 Apr 16 '19 at 02:52
  • @UpQuark Yes exactly, I want to know how to read and use token on front-end application. – vishwas-trivedi Apr 16 '19 at 02:54
  • @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. – vishwas-trivedi Apr 16 '19 at 02:59
  • @CamiloTerevinto I assumed from the linked article that this would be a common practice in web application development. – vishwas-trivedi Apr 16 '19 at 03:00
  • So i do not understand your question fully. However, have looked at this guide. https://jonhilton.net/2017/10/11/secure-your-asp.net-core-2.0-api-part-1---issuing-a-jwt/ – Cody Popham Apr 16 '19 at 04:41
  • @CodyPopham Please take a look at the definition in my question. My problem is API knows about authorization but how should I inform client app, I want to redirect based on the user's role(claim). – vishwas-trivedi Apr 16 '19 at 05:53
  • @CodyPopham API can know about user's role from token information but how can I decide for client app where to redirect based on token?? – vishwas-trivedi Apr 16 '19 at 05:54
  • @CodyPopham I want to create a single login form and redirect based on the user's role. – vishwas-trivedi Apr 16 '19 at 05:56
  • What is your client page? How will you request web api jwt-auth from client page? – Edward Apr 17 '19 at 02:49
  • @TaoZhou Client application will ASP.NET Core(MVC) RazorPage. Yes I will be requesting api from client page. – vishwas-trivedi Apr 17 '19 at 09:00
  • How will you request api, by ajax or c# code in razor page? Share us the related code – Edward Apr 17 '19 at 09:05
  • @TaoZhou using C# code in razor page – vishwas-trivedi Apr 17 '19 at 12:04
  • @TaoZhou I have created API based on the above link please check the original post – vishwas-trivedi Apr 17 '19 at 12:05
  • @VishwasTrivedi You put that information in the claims, which is used to populate the token. – Cody Popham Apr 18 '19 at 21:18

1 Answers1

0

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(){ }
Cody Popham
  • 992
  • 5
  • 14
  • 1
    This seems to be the code of API side. I'm not facing any problem with issuing token from API side with claims, the problem is how to use that claim on client side(website) to login based on user role. – vishwas-trivedi Apr 19 '19 at 01:31