我编写代码来生成JWT并使用证书对其进行签名,但是在我不想要的标题中添加kid
属性。如何使用没有此属性的证书创建JWT?这是我的代码:
public string CreateToken(string thumbprint, string iss, string sub, string aud, int lifetime)
{
X509Certificate2 cert = null;
var certificateStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
var lifeDuration = new Lifetime(DateTime.Now, DateTime.Now.AddMinutes(lifetime));
var tokenHandler = new JwtSecurityTokenHandler();
certificateStore.Open(OpenFlags.ReadOnly);
foreach (var certificate in certificateStore.Certificates)
{
if (certificate == null || certificate.Thumbprint == null)
{
continue;
}
if (string.Equals(certificate.Thumbprint, thumbprint, StringComparison.CurrentCultureIgnoreCase))
{
certificateStore.Close();
cert = certificate;
break;
}
}
if (cert == null)
{
throw new Exception("Certificate cannot be found!");
}
var signingCredentials = new SigningCredentials(new X509SecurityKey(cert), SecurityAlgorithms.RsaSha256Signature);
var tokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor
{
Issuer = iss,
Subject = new ClaimsIdentity(new Claim[]
{
new Claim("sub", sub),
new Claim("jti", Guid.NewGuid().ToString())
}),
Audience = aud,
Expires = lifeDuration.Expires,
SigningCredentials = signingCredentials
};
Microsoft.IdentityModel.Tokens.SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
string tokenString = tokenHandler.WriteToken(token);
return tokenString;
}
上面的代码会生成此令牌:
{
"alg": "RS256",
"kid": "B8C72D1B7A713A09372F2376094CC525A023379C",
"typ": "JWT"
}
{
"jti": "216fcf32-d4ae-4b5a-a255-79733b2e4535",
"exp": "1506496792",
"iat": "1506496792",
"iss": "issuer",
"aud": "audience",
"sub": "subject"
}
答案 0 :(得分:0)
我已经将我的方法改为这样,现在它可以正常工作
public string CreateToken(string thumbprint, string iss, string sub, string aud, int lifetime)
{
var lifeDuration = new Lifetime(DateTime.Now, DateTime.Now.AddMinutes(lifetime));
var cert = this.FindCertificate(thumbprint);
var signingCredentials = new SigningCredentials(new X509SecurityKey(cert), SecurityAlgorithms.RsaSha256Signature);
JwtHeader header = new JwtHeader(signingCredentials);
header.Clear();
header.Add("alg", "RS256");
header.Add("typ", "JWT");
JwtPayload payload = new JwtPayload(
iss,
aud,
new List<Claim>()
{
new Claim("sub", sub),
new Claim("jti", Guid.NewGuid().ToString())
},
null,
lifeDuration.Expires);
var jwt = new JwtSecurityToken(header, payload);
var encoded = new JwtSecurityTokenHandler().WriteToken(jwt);
return encoded;
}