0

I have this bit of code on the c# .NET server side that returns token to the Angular2 client. Is there any documentation describing how to interpret that on the java script angular side (which classes and its members to use to parse it properly)

private string generateJwtToken(Account account)
{
    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new[] { new Claim(/* "id" */ClaimTypes.NameIdentifier, account.Id.ToString()) }),
        Expires = DateTime.UtcNow.AddMinutes(15),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
    };
    var token = tokenHandler.CreateToken(tokenDescriptor);
    return tokenHandler.WriteToken(token);
}

Client side parsing:

var exp = this.accountValue.jwtToken.split('.')[1];
        
        const jwtToken = JSON.parse(atob(this.accountValue.jwtToken.split('.')[1]));

        // set a timeout to refresh the token a minute before it expires
        const expiresUtc = new Date(jwtToken.exp);
        const expires = new Date(jwtToken.exp * 1000);
        const mins = expires.getTime() - Date.now();
        const timeout = expires.getTime() - Date.now() - (60 * 1000);
        this.refreshTokenTimeout = setTimeout(() => this.refreshToken().subscribe(), timeout);
Janusz Dalecki
  • 197
  • 1
  • 10
  • Does this answer your question? [How to decode jwt token in javascript without using a library?](https://stackoverflow.com/questions/38552003/how-to-decode-jwt-token-in-javascript-without-using-a-library) – Drenai Jul 24 '22 at 07:08

1 Answers1

0

The token is not meant to be parsed on the client, it's just stored and sent with any subsequent request. If you need data like username, role on the client, just send them along with the token in the authentication response.

bgman
  • 309
  • 1
  • 5
  • The token is parsed on the client side - I just don't understand it and looking for some good documentation that explains it. Look at the client parsing code I have added to my original question. – Janusz Dalecki Jul 24 '22 at 10:27
  • You're right, you can parse and extract the expire time of the token. Look at https://www.npmjs.com/package/jwt-decode, if you need to extract other values. – bgman Jul 24 '22 at 13:09