使用 x509 证书签署 JWT 令牌时遇到问题 [英] Trouble signing a JWT token with an x509 Certificate

查看:47
本文介绍了使用 x509 证书签署 JWT 令牌时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用我创建的证书签署 JWT 令牌时遇到问题.我了解签名(公钥/私钥)如何工作的基本原理,但是类和工具集非常混乱.我已经对这个示例代码大惊小怪了很长一段时间,现在我完全陷入了困境.当我运行附加的示例代码时,我最终遇到以下错误(在 tokenHandler.CreateToken() 调用上):

I'm having trouble signing a JWT token with a certificate that I created. I understand the fundamentals of how signing (public/private key) works, but the classes and toolsets are very confusing. I've been fussing with this example code for quite a while, and I'm fully stuck now. When I run the attached example code I end up with the following error (on the tokenHandler.CreateToken() call):

System.NotSupportedException: 'IDX10634: 无法创建签名提供者.算法:'[PII 隐藏]',SecurityKey:'[PII 是不支持隐藏]'.'

System.NotSupportedException: 'IDX10634: Unable to create the SignatureProvider. Algorithm: '[PII is hidden]', SecurityKey: '[PII is hidden]' is not supported.'

我提供了我在 CertificatePfxFileBase64Encoded 变量 base64 编码中创建的证书.这是一个 .pfx 文件,其中嵌入了私钥,没有密码.它是一个二进制文件,所以我必须进行 base64 编码才能在此处共享.我试图很好地理解这些课程是如何工作的,但我无法克服这个障碍.有任何想法吗?下面的例子应该是完全独立的,你只需要收集参考资料.

I've provided the certificate I created in the CertificatePfxFileBase64Encoded variable base64 encoded. It's a .pfx file with the private key embedded in it with no password. Its a binary file so I had to base64 encoded in order to share it here. I'm trying to get a good understanding of how these classes work but I can't get past this hurdle. Any ideas? The example below should be fully self contained, you just have to gather the references.

using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;

namespace SecurityStuff
{
    public class Testing
    {
        static string CertificatePfxFileBase64Encoded = @"
MIIJqQIBAzCCCW8GCSqGSIb3DQEHAaCCCWAEgglcMIIJWDCCBA8GCSqGSIb3DQ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bQVGZXQSygwMTAhMAkGBSsOAwIaBQAEFE5XVOAJU286
B1gJ8j4mJ7HmXhEABAjfmw/u2zlmsAICCAA=";

        public static string CreateTokenWithX509SigningCredentials()
        {
            var signingCert = new X509Certificate2(Convert.FromBase64String(CertificatePfxFileBase64Encoded));

            var privateKey = new X509SecurityKey(signingCert);
            var algo = privateKey.PrivateKey.SignatureAlgorithm;
            var signingCredentials = new SigningCredentials(privateKey, algo);

            var now = DateTime.Now;
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                        {
                        new Claim(ClaimTypes.Name, "John"),
                        new Claim(ClaimTypes.Role, "Sales"),
                        }),
                Issuer = "self",
                IssuedAt = now,
                NotBefore = now,
                Expires = now.AddMinutes(50),
                //SigningCredentials = new X509SigningCredentials(signingCert),     //For some reason this class no longer exists
                SigningCredentials = signingCredentials,
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
            string tokenString = tokenHandler.WriteToken(token);

            return tokenString;
        }
    }
}

==== 编辑 ====

我认为展示我如何制作签名证书可能会有所帮助,因为问题可能出在那儿.下面是我用来生成证书 CertificatePfxFileBase64Encoded 的命令行.我使用应用程序 openSSL 来生成它.

I thought it might be helpful to show how I made the signing certificate because maybe the problem lies in there. Below are the command lines I used to generate my certificate CertificatePfxFileBase64Encoded. I used the application openSSL to generate it.

openssl req -new -newkey rsa:2048 -nodes -keyout CA_PrivateKey.key -out CA_SigningRequest.csr 

openssl x509 -req -days 2000 -in CA_SigningRequest.csr -signkey CA_PrivateKey.key -out CA_Certificate.crt 

openssl pkcs12 -export -out CA_Certificate.pfx -inkey CA_Private.key -in CA_Certificate.crt 

推荐答案

以下代码从 .pfx 文件生成 JWT 令牌.

The following code generates a JWT token from a .pfx file.

public static string GenerateToken(int expireMinutes)
{
    X509Certificate2 signingCert = new X509Certificate2("PFXFilePath", "password");
    X509SecurityKey privateKey = new X509SecurityKey(signingCert);
    var now = DateTime.UtcNow;
    var tokenHandler = new JwtSecurityTokenHandler();
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Expires = now.AddMinutes(Convert.ToInt32(expireMinutes)),
        SigningCredentials = new SigningCredentials(privateKey, SecurityAlgorithms.RsaSha256Signature)
    };
    JwtSecurityToken stoken = (JwtSecurityToken)tokenHandler.CreateToken(tokenDescriptor);
    string token = tokenHandler.WriteToken(stoken);
    return token;
}

这篇关于使用 x509 证书签署 JWT 令牌时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆