尝试在Dot Net Core 2.0中解码JWT

时间:2018-09-05 10:54:54

标签: c# .net-core jwt

我正在尝试测试一些功能,在这些功能中,我们解码JWT字符串并返回JwtSecurityToken对象。但是,使用共享密钥来帮助我进行验证时遇到了一些问题。我认为我做错了事,但在找到问题根源时遇到了一些问题。

现在,我正在尝试解码字符串

private JwtSecurityToken GetJsonWebTokenFromCookie()
{
    var cookieValueFromContext = HttpContext.Request.Cookies[".FAPPSOJWT"];

    Logger.LogInformation($"cookieValueFromContext: {cookieValueFromContext}");

#if DEBUG
            cookieValueFromContext = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1laWQiOiI5MDg4MjczNiIsInVuaXF1ZV9uYW1lIjoibWljaGFlbC5tb3JhbGVzQGljZS5vcmcudWsiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL2FjY2Vzc2NvbnRyb2xzZXJ2aWNlLzIwMTAvMDcvY2xhaW1zL2lkZW50aXR5cHJvdmlkZXIiOiJBU1AuTkVUIElkZW50aXR5IiwiQXNwTmV0LklkZW50aXR5LlNlY3VyaXR5U3RhbXAiOiIxZGNhNDQwNC1mMDBlLTQxZWEtOTYwNi03NjE3YWM3YmE3MmQiLCJnaXZlbl9uYW1lIjoiTWljaGFlbCBzYXBwc29hdHRhY2hlZG9uZSIsInJvbGUiOiJUcmFpbmVlIiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MjM2NyIsImF1ZCI6IjQxNGUxOTI3YTM4ODRmNjhhYmM3OWY3MjgzODM3ZmQxIiwiZXhwIjoxNTM2MTM0MDU1LCJuYmYiOjE1MzYwNDc2NTV9.4bvW_MAsXW3WmQXPkHtDXP0PO1m1jyDaiqlmtgI7qOI";
#endif

   if (string.IsNullOrEmpty(cookieValueFromContext)) return null;

   string secret = "5043651CD3E2AF73666D216855E5D59F83C4421DB051A44D";
   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(cookieValueFromContext, validations, out var tokenSecure);

    return (JwtSecurityToken) tokenSecure;
}

这是我得到的错误:

Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException: 'IDX10503: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey , KeyId: 
'.
Exceptions caught:
 ''.
token: '{"alg":"HS256","typ":"JWT"}.{"nameid":"90882736","unique_name":"michael.morales@ice.org.uk","http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider":"ASP.NET Identity","AspNet.Identity.SecurityStamp":"1dca4404-f00e-41ea-9606-7617ac7ba72d","given_name":"Michael sappsoattachedone","role":"Trainee","iss":"http://localhost:52367","aud":"414e1927a3884f68abc79f7283837fd1","exp":1536134055,"nbf":1536047655}'.'

在这一行:

 var claims = handler.ValidateToken(cookieValueFromContext, validations, out var tokenSecure);

出于测试目的,我使用#IF DEBUG只是为了确保代码在使用cookie之前可以正常工作。

任何帮助或建议,将不胜感激。

这也是JWT.IO上JWT的图像

enter image description here

0 个答案:

没有答案