Search code examples
c#asp.net-corejwt

How can I use X509SecurityKey for Asp.Net Core JWT validation?


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?


Solution

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