2

I am using the following code to generate JWT token.

        string audienceId = "099153c2625149bc8ecb3e85e03f0022";
        string secretKey = "IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw";
        var keyByteArray = TextEncodings.Base64Url.Decode(secretKey);

        var issued = data.Properties.IssuedUtc;
        var expires = data.Properties.ExpiresUtc;

        IList<Claim> claimCollection = new List<Claim>
        {
            new Claim(ClaimTypes.Name, "Test")
            , new Claim(ClaimTypes.Country, "Sweden")
            , new Claim(ClaimTypes.Gender, "M")
            , new Claim(ClaimTypes.Surname, "Nemes")
            , new Claim(ClaimTypes.Email, "hello@me.com")
            , new Claim(ClaimTypes.Role, "IT")
        };

        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject =  new ClaimsIdentity(claimCollection),
            Issuer = _issuer,
            Audience = audienceId,
            Expires = expires.Value.DateTime,
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(keyByteArray), SecurityAlgorithms.HmacSha256)
        };
        var tokenHandler = new JwtSecurityTokenHandler();

        var securityToken = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(securityToken);`

if i validate the generated code in https://jwt.io/ it turns out invalid signature.

Am using the following to validate token.

        var token = new JwtSecurityToken(model.Token);
        string ClientId = "099153c2625149bc8ecb3e85e03f0022";
        string Base64Secret = "IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw";
        var keyByteArray = TextEncodings.Base64Url.Decode(Base64Secret);

        var validationParameters = new TokenValidationParameters
        {
            IssuerSigningKey = new SymmetricSecurityKey(keyByteArray),
            ValidIssuer = "CBEAE4B7-A490-430A-85C7-865D051C21E6",
            ValidAudience = ClientId
        };

        var tokenHandler = new JwtSecurityTokenHandler();

        SecurityToken validatedToken;
        ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(model.Token, validationParameters, out validatedToken);

I receive exception as Invalid Signature. There is very less documentation available with latest version of System.IdentityModel.Tokens.Jwt (version 5.1.4). Please note i cannot downgrade the dll as well.

I am not sure where i am going wrong. Appreciate any help on this.

user2603610
  • 323
  • 1
  • 2
  • 10

1 Answers1

1

Try and use a different decoder for your validation as suggested by Iris here

My scenario was I have a ASP.NET JWT AuthorizationServer and needed to authenticate with ASPNET CORE JWT ResourceServer and the below code worked for me.

public static class Base64UrlTextEncoder /*: ITextEncoder*/
    {
        public static string Encode(byte[] data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            return Convert.ToBase64String(data).TrimEnd('=').Replace('+', '-').Replace('/', '_');
        }

        public static byte[] Decode(string text)
        {
            if (text == null)
            {
                throw new ArgumentNullException("text");
            }

            return Convert.FromBase64String(Pad(text.Replace('-', '+').Replace('_', '/')));
        }

        private static string Pad(string text)
        {
            var padding = 3 - ((text.Length + 3) % 4);
            if (padding == 0)
            {
                return text;
            }
            return text + new string('=', padding);
        }
    }

Usage

var base64key = Base64UrlTextEncoder.Decode("IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw");
var issuerSigningKey = new SymmetricSecurityKey(base64key);
bluee
  • 997
  • 8
  • 18