我正在尝试加载私钥以签署JWT令牌。我得到以下代码,但出现异常失败:
string key =@"-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCTLOQaZ3D0ayC1BSW4LCs3gYmu
eYiWDGRT491PJt/4
-----END PRIVATE KEY-----";
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha512);
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha512);
var header = new JwtHeader(signingCredentials);
var t = DateTime.UtcNow - new DateTime(1970, 1, 1);
int iat = (int)t.TotalSeconds;
var payload = new JwtPayload
{
{ "iss", "1234-5678-9012-1221-11111"},
{ "iat", iat },
{ "exp", iat + 900},
{ "sub", "aaaaaaaaaaa" }
};
var secToken = new JwtSecurityToken(header, payload);
var tokenString = new JwtSecurityTokenHandler().WriteToken(secToken);
===============答案===============================
对于任何面临相同问题的人,这就是解决方案。您需要阅读底部的文章才能使其正常工作:
http://www.donaldsbaconbytes.com/2016/08/create-jwt-with-a-private-rsa-key/
答案 0 :(得分:0)
您的问题出在下面的行
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha512);
您正在尝试将对称密钥与非对称算法(RSA算法)一起使用。
您可以寻找其他对称算法来生成signingCredentials
,如下所示
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature);