3

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?

SledgeHammer
  • 7,338
  • 6
  • 41
  • 86
  • See similar issue https://github.com/IdentityServer/IdentityServer4/issues/61 It seems the problem is about signature algorithm. – adem caglin Sep 14 '16 at 19:21

1 Answers1

8

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)
Kévin Chalet
  • 39,509
  • 7
  • 121
  • 131
  • Thanks, it works with RsaSha512. I also had to recreate the cert with an embedded private key. – SledgeHammer Sep 14 '16 at 21:23
  • @PinPoint I have a similiar question, mind helping me out over there please: https://stackoverflow.com/questions/46294373/net-core-issuersigningkey-from-file-for-jwt-bearer-authentication – monty Sep 19 '17 at 11:39