[英]How to sign/unsign JWT token using certificates from a pfx file with c#?
I'm using asp.net core and I want to sent (POST) a JWT token that is signed using a private key from a .pfx.我正在使用asp.net 核心,我想发送(POST)一个使用 .pfx 中的私钥签名的 JWT 令牌。 file.文件。 The receiver side must be able to validate the token using the public key from the .pfx file.在接收端必须能够验证令牌使用从.pfx文件的公钥。
How do I do that?我怎么做?
Found the solution:找到了解决办法:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.