【发布时间】:2020-03-12 13:43:48
【问题描述】:
我正在使用 asp.net core,我想发送 (POST) 一个 JWT 令牌,该令牌使用来自 .pfx 的 private 密钥进行签名。文件。 接收方必须能够使用 .pfx 文件中的 public 密钥验证令牌。
我该怎么做?
【问题讨论】:
标签: c# asp.net-core jwt
我正在使用 asp.net core,我想发送 (POST) 一个 JWT 令牌,该令牌使用来自 .pfx 的 private 密钥进行签名。文件。 接收方必须能够使用 .pfx 文件中的 public 密钥验证令牌。
我该怎么做?
【问题讨论】:
标签: c# asp.net-core jwt
找到解决方案:
string certPath = @"xxxx";
string certPass = "xxxx";
var collection = new X509Certificate2Collection();
collection.Import(certPath, certPass, X509KeyStorageFlags.PersistKeySet);
var certificate = collection[0];
// create the token signed with privaet key
// 1. create private security key to create the token
var rsaPrivateKey = certificate.GetRSAPrivateKey();
var privateSecurityKey = new RsaSecurityKey(rsaPrivateKey);
var descriptor = new SecurityTokenDescriptor
{
Issuer = "me",
Audience = "you",
IssuedAt = DateTime.UtcNow,
NotBefore = DateTime.UtcNow,
Expires = DateTime.UtcNow.AddMinutes(5),
Subject = new ClaimsIdentity(new List<Claim> { new Claim("sub", "scott") }),
SigningCredentials = new SigningCredentials(privateSecurityKey, SecurityAlgorithms.RsaSha256Signature)
};
var handler = new JsonWebTokenHandler();
// 2. create the token
string jwt = handler.CreateToken(descriptor);
// validate token using public key
var rsaPublicKey = certificate.GetRSAPublicKey();
var publicSecurityKey = new RsaSecurityKey(rsaPublicKey);
var result = handler.ValidateToken(jwt,
new TokenValidationParameters
{
ValidIssuer = "me",
ValidAudience = "you",
IssuerSigningKey = publicSecurityKey
});
Assert.True(result.IsValid);
【讨论】: