Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Token handler unable to convert the token to jwt token

I'm trying to convert my token string to jwt token using JwtSecurityTokenHandler. But it's getting error that saying

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

How can I solve this issue?

Here is my token

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImFkbWluIiwibmJmIjoxNTUwNjM3NzcxLCJleHAiOjE1NTA2Mzg5NzEsImlhdCI6MTU1MDYzNzc3MX0.tUcoyoHgkrX3rDKl0cRLd9FwLtRprQpgYepMoiekixY

var tokenHandler = new JwtSecurityTokenHandler();
var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken;

Calling web api

using (HttpClient client = new HttpClient())
            {
                string path = "UserMaintenance/ValidateUserId?userid=" + txtUsername.Text.Trim().ToString();
                client.BaseAddress = new Uri(GlobalData.BaseUri);
                client.DefaultRequestHeaders.Add("Authorization", "Bearer" + GlobalData.Token);
                HttpResponseMessage response = client.GetAsync(path).Result;
                if (response.IsSuccessStatusCode)
                {
                    var value = response.Content.ReadAsStringAsync().Result;
                    isValid = JsonConvert.DeserializeObject<bool>(value);
                }
            }

Here is my GetPrincipal method

public static ClaimsPrincipal GetPrincipal(string token)
    {
        try
        {
            var symmetricKey = Convert.FromBase64String(Secret);
            var validationParameters = new TokenValidationParameters()
            {
                RequireExpirationTime = true,
                ValidateIssuer = false,
                ValidateAudience = false,
                IssuerSigningKey = new SymmetricSecurityKey(symmetricKey)
            };

            var handler = new JwtSecurityTokenHandler();
            handler.InboundClaimTypeMap.Clear();

            SecurityToken securityToken;
            var principal = handler.ValidateToken(token, validationParameters, out securityToken);

            return principal;
        }

        catch (Exception ex)
        {
            return null;
        }
    }
like image 333
thilim9 Avatar asked Feb 20 '19 04:02

thilim9


People also ask

What is JWT token error?

This error occurs if the JSON Web Token (JWT) specified in the <Source> element of the Decode JWT policy is malformed, invalid or otherwise not decodable. A properly structured JWT should contain a header, payload and signature in the following format: header.

How to check if JWT token is valid or not?

To verify JWT claimsVerify that the token is not expired. The aud claim in an ID token and the client_id claim in an access token should match the app client ID that was created in the Amazon Cognito user pool. The issuer ( iss ) claim should match your user pool.

How to verify signature in JWT?

Go to Dashboard > Applications. Go to the Settings view, and open Advanced Settings. Go to the Certificates view, locate the Signed Certificate field, and copy the Public Key. Navigate to the JWT.io website, locate the Algorithm dropdown, and select RS256.

What is JWT in C #?

JWT (JSON web token) has become more and more popular in web development. It is an open standard which allows transmitting data between parties as a JSON object in a secure and compact way. The data transmitting using JWT between parties are digitally signed so that it can be easily verified and trusted.


1 Answers

This is how I do it and it works for me:

var token = new System.IdentityModel.Tokens.JwtSecurityToken(jwt);  

The above line works for System.IdentityModel.Tokens.Jwt package version 4.0.0. As @Nick commented, in the latest versions of the package, the JwtSecurityToken does not exist in the previous namespace anymore, instead it exists in System.IdentityModel.Tokens.Jwt so you need to write: var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(jwt);

Unless your token is not well-formed. It would be better if you share the token too.

Update:

You also need to remove the word "Bearer " from the beginning of the token (If you haven't):

 var jwt = context.Request.Headers["Authorization"].Replace("Bearer ", string.Empty);
like image 182
Amir Molaei Avatar answered Oct 28 '22 12:10

Amir Molaei