Decode JWT Token

Decoding JWT token and return value;

protected string GetCalimValue(string token)
{
   var handler = new JwtSecurityTokenHandler();
   var jsonToken = handler.ReadToken(token);
   var tokenJWT = jsonToken as JwtSecurityToken;
   //var jwtSecurityToken = handler.ReadJwtToken(token);

   var jti = tokenJWT.Claims.First(claim => claim.Type == "jti").Value;
   return jti;
}

Validating and Decoding JWT Token and return value;

protected string ValidateTokenAndGetClaimValue(string token)
{
    string secret = "this is a string used for encrypt and decrypt token";
    var key = Encoding.ASCII.GetBytes(secret);
    var handler = new JwtSecurityTokenHandler();
    var validations = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(key),
        ValidateIssuer = false,
        ValidateAudience = false
    };
    var claims = handler.ValidateToken(token, validations, out var tokenSecure);

    var tokenJWT = tokenSecure as JwtSecurityToken;
    var emailAddress = tokenJWT.Claims.First(claim => claim.Type == "email").Value;
    return emailAddress;
}

We want to keep token inside cookies on a successful token acquisition;

Response.Cookies.Append("X-Access-Token", login.JwToken, new CookieOptions() { HttpOnly = true, SameSite = SameSiteMode.Strict });
Response.Cookies.Append("X-Email", login.Email, new CookieOptions() { HttpOnly = true, SameSite = SameSiteMode.Strict });

References

https://stackoverflow.com/questions/38340078/how-to-decode-jwt-token

https://www.codemag.com/Article/2105051/Implementing-JWT-Authentication-in-ASP.NET-Core-5

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect