简体   繁体   中英

Is there a way to interpret token created by c# app on the Angular2 client side

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM