【问题标题】:How to sign/unsign JWT token using certificates from a pfx file with c#?如何使用 c# 中的 pfx 文件中的证书对 JWT 令牌进行签名/取消签名?
【发布时间】:2020-03-12 13:43:48
【问题描述】:

我正在使用 asp.net core,我想发送 (POST) 一个 JWT 令牌,该令牌使用来自 .pfx 的 private 密钥进行签名。文件。 接收方必须能够使用 .pfx 文件中的 public 密钥验证令牌。

我该怎么做?

【问题讨论】:

    标签: c# asp.net-core jwt


    【解决方案1】:

    找到解决方案:

            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);
    

    【讨论】:

      猜你喜欢
      • 2016-12-08
      • 2020-04-17
      • 2019-11-01
      • 2011-05-11
      • 1970-01-01
      • 2018-05-29
      • 2011-08-12
      • 2010-10-22
      • 2012-08-13
      相关资源
      最近更新 更多