Невозможно проверить токен JWT - PullRequest
0 голосов
/ 07 марта 2019

Я использую следующий код для генерации строки токена.

string key = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";

            //// Create Security key  using private key above:
            //// not that latest version of JWT using Microsoft namespace instead of System
            var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));

            ////Also note that securityKey length should be >256b
            ////so you have to make sure that your private key has a proper length
            ////
            var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

            ////  Finally create a Token
            var header = new JwtHeader(credentials);

            ////Some PayLoad that contain information about the  customer
            var payload = new JwtPayload
               {
                   {
                    "some ", "hello "
                },
                   {
                    "scope", "http://dummy.com/"
                },
               };


            var secToken = new JwtSecurityToken(header, payload);

            var tokenString1 = handler.WriteToken(secToken);

            Console.WriteLine(tokenString);
            Console.WriteLine("Consume Token");



            var token = handler.ReadJwtToken(tokenString);

Сейчас, когда я пытаюсь проверить токен с помощью следующего кода, получаю сообщение об ошибке:

// Just to validate the authenticity of the certificate. 
        var tokenValidationParameters = new TokenValidationParameters
        {


            ValidateIssuer = false,
            ValidateAudience = false,
            ValidateLifetime = false,
            ValidateIssuerSigningKey = false,

            IssuerSigningKeys = GetEmbeddedKeys(jwtSecurityToken)
        };

        // Perform the validation 
        var tokenHandler = new JwtSecurityTokenHandler();
        SecurityToken validatedToken;
        try
        {
            tokenHandler.ValidateToken(jwtTokenRequest.ClientJwtTokenString, tokenValidationParameters, out validatedToken);
        }
        catch (ArgumentException)
        {
            throw EnumException.Create(LicenseClientJwtError.FailedToValidateJwtTokenSignature, string.Format(CultureInfo.InvariantCulture, "PostParseJwtToken - Failed to validate JWT Token Signature. The Token does not have 3 or 5 parts {0}", jwtTokenRequest.ClientJwtTokenString));
        }

private static X509SecurityKey[] GetEmbeddedKeys(JwtSecurityToken token)
    {

        X509SecurityKey[] keys = null;
        if (token.Header.TryGetValue("x5c", out var certificateAsString))
        {
            keys = (certificateAsString as JArray).Values<string>().Select(x => new X509SecurityKey(new X509Certificate2(Convert.FromBase64String(x)))).ToArray();
            return keys;
        }

        return null;
    }

получаюjwtTokenRequest.ClientJwtTokenString = "eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lICI6ImhlbGxvICIsInNjb3BlIjoiaHR0cDovL2R1bW15LmNvbS8ifQ.FPkHESpldjwEsdE_ii8936gFq4pfptl3b6ao13BTLZk"

1008 * Подводит следующее сообщение об ошибке при проверке.Error

Любая помощь будет принята с благодарностью.

...