I don't understand how this library works. Could you help me please ?

Here is my simple code :

public void TestJwtSecurityTokenHandler()
        var stream =
        var handler = new JwtSecurityTokenHandler();

        var jsonToken = handler.ReadToken(stream);

This is the error :

The string needs to be in compact JSON format, which is of the form: Base64UrlEncodedHeader.Base64UrlEndcodedPayload.OPTIONAL,Base64UrlEncodedSignature'.

If you copy the stream in jwt.io website, it works fine :)


Ответов: 7

Ответы (7)

I found the solution, I just forgot to Cast the result:

var stream = "[encoded jwt]";  
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(stream);
var tokenS = jsonToken as JwtSecurityToken;

Or, without the cast:

var token = "[encoded jwt]";  
var handler = new JwtSecurityTokenHandler();
var jwtSecurityToken = handler.ReadJwtToken(token);

I can get Claims using:

var jti = tokenS.Claims.First(claim => claim.Type == "jti").Value;

new JwtSecurityTokenHandler().ReadToken("") will return a SecurityToken

new JwtSecurityTokenHandler().ReadJwtToken("") will return a JwtSecurityToken

If you just change the method you are using you can avoid the cast in the above answer

  var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
  var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
  var claims = new[]
      new Claim(JwtRegisteredClaimNames.Email, model.UserName),
      new Claim(JwtRegisteredClaimNames.NameId, model.Id.ToString()),
  var token = new JwtSecurityToken(_config["Jwt:Issuer"],
      expires: DateTime.Now.AddMinutes(30),
      signingCredentials: creds);

Then extract content

 var handler = new JwtSecurityTokenHandler();
 string authHeader = Request.Headers["Authorization"];
 authHeader = authHeader.Replace("Bearer ", "");
 var jsonToken = handler.ReadToken(authHeader);
 var tokenS = handler.ReadToken(authHeader) as JwtSecurityToken;
 var id = tokenS.Claims.First(claim => claim.Type == "nameid").Value;

You need the secret string which was used to generate encrypt token. This code works for me:

protected string GetName(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);
        return claims.Identity.Name;

I write this solution and it's work for me

    protected Dictionary GetTokenInfo(string token)
        var TokenInfo = new Dictionary();

        var handler = new JwtSecurityTokenHandler();
        var jwtSecurityToken = handler.ReadJwtToken(token);
        var claims = jwtSecurityToken.Claims.ToList();

        foreach (var claim in claims)
            TokenInfo.Add(claim.Type, claim.Value);

        return TokenInfo;

Extending on cooxkie answer, and dpix answer, when you are reading a jwt token (such as an access_token received from AD FS), you can merge the claims in the jwt token with the claims from "context.AuthenticationTicket.Identity" that might not have the same set of claims as the jwt token.

To Illustrate, in an Authentication Code flow using OpenID Connect,after a user is authenticated, you can handle the event SecurityTokenValidated which provides you with an authentication context, then you can use it to read the access_token as a jwt token, then you can "merge" tokens that are in the access_token with the standard list of claims received as part of the user identity:

    private Task OnSecurityTokenValidated(SecurityTokenValidatedNotification context)
        //get the current user identity
        ClaimsIdentity claimsIdentity = (ClaimsIdentity)context.AuthenticationTicket.Identity;

        /*read access token from the current context*/
        string access_token = context.ProtocolMessage.AccessToken;

        JwtSecurityTokenHandler hand = new JwtSecurityTokenHandler();
        //read the token as recommended by Coxkie and dpix
        var tokenS = hand.ReadJwtToken(access_token);
        //here, you read the claims from the access token which might have 
        //additional claims needed by your application
        foreach (var claim in tokenS.Claims)
            if (!claimsIdentity.HasClaim(claim.Type, claim.Value))

        return Task.FromResult(0);

Using .net core jwt packages, the Claims are available:

[Authorize(Policy = "Bearer")]
public class AbstractController: ControllerBase
    protected string UserId()
        var principal = HttpContext.User;
        if (principal?.Claims != null)
            foreach (var claim in principal.Claims)
               log.Debug($"CLAIM TYPE: {claim.Type}; CLAIM VALUE: {claim.Value}");

        return principal?.Claims?.SingleOrDefault(p => p.Type == "username")?.Value;

2022 WebDevInsider