Ibanez1408
Ibanez1408

Reputation: 5048

How to get the roles from a JWT token from a web api in Angular

I need to get the roles from my JWT token which was created in asp.net core using claims. This is the token I get:

FirstName: "Juan"
LastName: "Dela Cruz"
MiddleName: "A."
UserId: "2"
aud: "http://192.168.1.6:13735"
exp: 1590001134
http://schemas.microsoft.com/ws/2008/06/identity/claims/role: Array(2)
0: "User"
1: "Administrator"
length: 2
__proto__: Array(0)
iss: "http://192.168.1.6:13735"
jti: "5732c019-0f91-4e32-8f8d-93da43547346"
sub: "juan"

I get this using this code in my web api

var claims = new List<Claim>
                {
                    new Claim(JwtRegisteredClaimNames.Sub, applicationUser.UserName),
                    new Claim("UserId", applicationUser.Id.ToString()),
                    new Claim("FirstName", applicationUser.FirstName.ToString()),
                    new Claim("MiddleName", applicationUser.MiddleName.ToString()),
                    new Claim("LastName", applicationUser.LastName.ToString()),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
                };

                foreach(var role in roles)
                {
                    claims.Add(new Claim(ClaimTypes.Role, role.RoleName));
                }

                var validIssuer = configuration["WebToken:Issuer"];
                var validAudience = configuration["WebToken:Audience"];

                var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["AmsToken:TokenKey"]));
                var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                var tokenOptions = new JwtSecurityToken(
                        issuer: "http://192.168.1.6:13735",
                        audience: "http://192.168.1.6:13735",
                        claims: claims,
                        expires: DateTime.Now.AddHours(8),
                        signingCredentials: signinCredentials
                    );
                var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions);
                return Ok(new { Token = tokenString });

In my angular application, I need to get the roles so I can hide or show buttons accordingly. However, I do not know how to get the roles from the web token generated. This is how I get the roles from the Token:

 // Show or hide the navigation links
  roleMatch(): void {
    debugger;
    let isMatch = false;
    const payload = JSON.parse(window.atob(localStorage.getItem('authToken').split('.')[1]));
    const userRole = payload.role; ======> I get undefined on this part
  }

Could you pleas point out how to get what I need? Thank you.

Upvotes: 0

Views: 2717

Answers (1)

Alex Mongeot
Alex Mongeot

Reputation: 94

To decode the token you need a library, I personnaly use this one : https://github.com/auth0/angular2-jwt

Then you install it thanks to npm or another packet manager:

$ npm install @auth0/angular-jwt

You import the module and instanciate an instance of the JwtHelperService class :

import { JwtHelperService } from "@auth0/angular-jwt";

const helper = new JwtHelperService();

and then you should be able to decode your token :

const decodedToken = helper.decodeToken(myRawToken);

Upvotes: 1

Related Questions