Siddharth Kumar
Siddharth Kumar

Reputation: 333

Unable to read JWT token generated using System.IdentityModel.Tokens.Jwt

We have started development on a new project and are considering using Identity Server/OpenId for authorization and Authentication needs. Since I have not worked with Jwt tokens before I was reading up on Microsoft's Jwt classes and support and trying out some sample code. I installed the System.Identitymodel.Tokend.Jwt version 5.4 from Nuget and generated the token using the sample code below (which I found on stack overflow)

        string strToken = string.Empty;

        string strKey = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";
        var vSymmetricSecurityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(strKey));
        var vSigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(vSymmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature);
        var header = new JwtHeader(vSigningCredentials);
        var payload = new JwtPayload
        {
            { "Id", "userId" },
            { "Role", "userrole" },
            { "FirstName", "first_name" },
            { "LastName", "last_name" },
            { "EmailAddress", "email_address" },
            { "TenantId", "tenant_id" },
        };
        var secToken = new JwtSecurityToken(header, payload);
        var handler = new JwtSecurityTokenHandler();
        strToken = handler.WriteToken(secToken);

The token was generated successfully. But when I go to read the token I get the following error

IDX12709: CanReadToken() returned false. JWT is not well formed: '[PII is hidden]'. The token needs to be in JWS or JWE Compact Serialization Format. (JWS): 'EncodedHeader.EndcodedPayload.EncodedSignature'. (JWE): 'EncodedProtectedHeader.EncodedEncryptedKey.EncodedInitializationVector.EncodedCiphertext.EncodedAuthenticationTag'.

If I paste the token in JWT - it tells me invalid signature. What could be incorrect?

The token generated is eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJJZCI6InVzZXJJZCIsIlJvbGUiOiJ1c2Vycm9sZSIsIkZpcnN0TmFtZSI6ImZpcnN0X25hbWUiLCJMYXN0TmFtZSI6Imxhc3RfbmFtZSIsIkVtYWlsQWRkcmVzcyI6ImVtYWlsX2FkZHJlc3MiLCJUZW5hbnRJZCI6InRlbmFudF9pZCJ9.BXUFKLcVmnGxRG5yGRNYVLTU2gT_F_AmBGev6sWhQd0

Upvotes: 0

Views: 8783

Answers (2)

Tropin Alexey
Tropin Alexey

Reputation: 766

In my case it was wrong OAuth Bearer Token. Double check it, for example it can have two times "Bearer" at the beginning of the string

Upvotes: 0

John Hanley
John Hanley

Reputation: 81454

You are using the wrong key type and algorithm. JWT uses public/private keys and not symmetric keys.

Also, there is a standard for the content of the JWT claims (payload). You are missing items such as the issued, expires at, etc. fields. Once you fix your signing problem create a new question if you need help with JWT claims as this is a very different subject.

Note: strKey should be the Private Key of the keypair. The Public Key is used to verify the signature of the JWT (called JWS).

Change these lines:

var vSymmetricSecurityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(strKey));
var vSigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(vSymmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature);

to:

var vRsaSecurityKey = new Microsoft.IdentityModel.Tokens.RsaSecurityKey(privateKey);
var vSigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(vSymmetricSecurityKey, SecurityAlgorithms.RsaSha256Signature);

Upvotes: 0

Related Questions