当前位置:  开发笔记 > 编程语言 > 正文

使用X509Certificate2(JwtSecurityTokenHandler)保护JWT

如何解决《使用X509Certificate2(JwtSecurityTokenHandler)保护JWT》经验,为你挑选了1个好方法。

我成功地完成了JwtSecurityTokenHandler工作X509Certificate2.我能够用一个X509Certificate2对象签署令牌.我还能够通过使用证书的原始数据通过X509Certificate2.RawData属性来验证令牌.

这是代码:

class Program
{
    static void Main(string[] args)
    {
        X509Store store = new X509Store("My");
        store.Open(OpenFlags.ReadOnly);
        X509Certificate2 signingCert = store.Certificates[0];

        string token = CreateTokenWithX509SigningCredentials(signingCert);
        ClaimsPrincipal principal = ValidateTokenWithX509SecurityToken(
            new X509RawDataKeyIdentifierClause(signingCert.RawData), token);
    }

    static string CreateTokenWithX509SigningCredentials(X509Certificate2 signingCert)
    {
        var now = DateTime.UtcNow;
        var tokenHandler = new JwtSecurityTokenHandler();
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, "Tugberk"),
                        new Claim(ClaimTypes.Role, "Sales"), 
                    }),
            TokenIssuerName = "self",
            AppliesToAddress = "http://www.example.com",
            Lifetime = new Lifetime(now, now.AddMinutes(2)),
            SigningCredentials = new X509SigningCredentials(signingCert)
        };

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

        return tokenString;
    }

    static ClaimsPrincipal ValidateTokenWithX509SecurityToken(X509RawDataKeyIdentifierClause x509DataClause, string token)
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var x509SecurityToken = new X509SecurityToken(new X509Certificate2(x509DataClause.GetX509RawData()));
        var validationParameters = new TokenValidationParameters()
        {
            AllowedAudience = "http://www.example.com",
            SigningToken = x509SecurityToken,
            ValidIssuer = "self",
        };

        ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(
            new JwtSecurityToken(token), validationParameters);

        return claimsPrincipal;
    }
}

我的主要问题是我应该从我的世界中揭露出什么X509Certificate2.我应该透露X509Certificate2的哪一部分,以便消费者应该验证JWT令牌但是不能使用相同的证书创建新令牌



1> woloski..:

您必须通过右键单击证书来公开您可以获得的公钥,并在MMC上执行导出(不包括私钥).那么谁必须验证令牌就行了

 var x509 = new X509Certificate2(pathToExportedCert);

或者您也可以使用字节数组ctor并使用base64编码公钥.

推荐阅读
虎仔球妈_459
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有