问题描述
我如何(我可以?)使用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]);
}
,然后获取签名凭据...
new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
这会导致异常:
SignatureAlgorithm:"HS256",SecurityKey:"Microsoft.IdentityModel.Tokens.X509SecurityKey" 不支持. 在Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateProvider(SecurityKey键,字符串算法,布尔值willCreateSignatures) 在Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForSigning(安全密钥,字符串算法)
我尝试了几种算法,但似乎不适用于其中任何一种?
您正在尝试将非对称密钥(嵌入X.509证书中)与HMAC算法(我们经常滥用称其为对称签名算法")一起使用:这不起作用. /p>
假设您的证书是RSA证书,则应该可以使用SecurityAlgorithms.RsaSha256
.
var credentials = new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha256)
How can I (can I?) use X509SecurityKey for Asp.Net Core JWT validation?
My current code is roughly:
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]);
}
and later on for the signing credentials...
new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
This causes an exception:
SignatureAlgorithm: 'HS256', SecurityKey: 'Microsoft.IdentityModel.Tokens.X509SecurityKey' is not supported. at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateProvider(SecurityKey key, String algorithm, Boolean willCreateSignatures) at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForSigning(SecurityKey key, String algorithm)
I tried a few algorithms, but it doesn't seem like it works with any of them?
You're trying to use an asymmetric key (embedded in a X.509 certificate) with a HMAC algorithm (that we often abusively call "symmetric signature algorithm"): this cannot work.
Assuming your certificate is a RSA certificate, you should be able to use SecurityAlgorithms.RsaSha256
.
var credentials = new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha256)
这篇关于如何使用X509SecurityKey进行Asp.Net Core JWT验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!