JWT令牌与System.IdentityModel.tokens.JWT版本5.1.4
我使用以下代码生成JWT令牌JWT令牌与System.IdentityModel.tokens.JWT版本5.1.4,jwt,Jwt,我使用以下代码生成JWT令牌 string audienceId = "099153c2625149bc8ecb3e85e03f0022"; string secretKey = "IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw"; var keyByteArray = TextEncodings.Base64Url.Decode(secretKey); var issued = data.
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);`
我收到异常作为无效签名。
最新版本的System.IdentityModel.Tokens.Jwt(版本5.1.4)提供的文档非常少。请注意,我不能降级的dll以及
我不确定我会错在哪里。非常感谢您在这方面的帮助。请按照Iris的建议,尝试使用不同的解码器进行验证 我的场景是我有一个ASP.NET JWT AuthorizationServer,需要通过ASPNET CORE JWT ResourceServer进行身份验证,下面的代码对我有效
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);
}
}
用法
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);
}
}
var base64key = Base64UrlTextEncoder.Decode("IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw");
var issuerSigningKey = new SymmetricSecurityKey(base64key);