我使用以下代码生成JWT令牌。
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);`
如果我在https://jwt.io/中验证生成的代码,则结果是无效的签名。
使用以下内容验证令牌。
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);
我收到异常作为无效签名。 最新版本的System.IdentityModel.Tokens.Jwt(版本5.1.4)提供的文档非常少。请注意我也不能降级dll。
我不确定我哪里出错了。感谢任何帮助。
答案 0 :(得分:1)
根据Iris here
的建议,尝试使用不同的解码器进行验证我的方案是我有一个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);
}
}
用法
var base64key = Base64UrlTextEncoder.Decode("IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw");
var issuerSigningKey = new SymmetricSecurityKey(base64key);