如何使用X509SecurityKey进行Asp.Net Core JWT验证?

Sle*_*mer 3 c# jwt asp.net-core

我怎么能(我可以?)使用X509SecurityKey进行Asp.Net Core JWT验证吗?

我目前的代码大致是:

        X509SecurityKey signingKey = null;

        using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
        {
            store.Open(OpenFlags.ReadOnly);
            var v = store.Certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, true);
            var v1 = v.Find(X509FindType.FindBySubjectDistinguishedName, strCertName, true);
            signingKey = new X509SecurityKey(v1[0]);
        }
Run Code Online (Sandbox Code Playgroud)

然后是签名凭证......

new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
Run Code Online (Sandbox Code Playgroud)

这会导致异常:

SignatureAlgorithm:'HS256',SecurityKey:'Microsoft.IdentityModel.Tokens.X509SecurityKey'不受支持.at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateProvider(SecurityKey key,String algorithm,Boolean willCreateSignatures)at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForSigning(SecurityKey key,String algorithm)

我尝试了一些算法,但它似乎不适用于它们中的任何一个?

Kév*_*let 6

我尝试了一些算法,但它似乎不适用于它们中的任何一个?

您正在尝试使用非对称密钥(嵌入在X.509证书中)和HMAC算法(我们经常滥用 "对称签名算法"):这不起作用.

假设您的证书是RSA证书,您应该可以使用SecurityAlgorithms.RsaSha256.

var credentials = new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha256)
Run Code Online (Sandbox Code Playgroud)