.NET Core IssuerSigningKey from file for JWT Bearer Authentication

前端 未结 2 1215
我在风中等你
我在风中等你 2020-12-14 02:45

I am struggling with the implementation (or the understanding) of signing keys for JWT Bearer Token authentication. And I hope somebody can help me or explain me what I am m

相关标签:
2条回答
  • 2020-12-14 03:08

    Oh dear, that simple:

    SecurityKey key = new X509SecurityKey(cert);
    

    Or as complete sample from above:

    X509Certificate2 cert = new X509Certificate2("MySelfSignedCertificate.pfx", "password");
    SecurityKey key = new X509SecurityKey(cert); //well, seems to be that simple
    app.UseJwtBearerAuthentication(new JwtBearerOptions
    {
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = "MyIssuer",
            ValidateAudience = true,
            ValidAudience = "MyAudience",
            ValidateLifetime = true,
            IssuerSigningKey = key
         }
    });
    
    0 讨论(0)
  • 2020-12-14 03:29

    A very important point, if you are using certificate files, that while the server requires the file with the private key, the client should only use the public key.

    You do not want to be giving your private key file to anyone; they only ever need the public key.

    // On client
    var publicCert = new X509Certificate2("MySelfSignedCertificate.cer");
    var publicKey = new X509SecurityKey(publicCert);
    ...
        IssuerSigningKey = publicKey
    

    The simplest way to convert the PFX (private) to CER (public) may be to import into the Windows certificate manager, then export with the public key only.

    From the command line, you can create also use PowerShell 5 (not yet in PowerShell 6):

    Get-PfxCertificate -FilePath MySelfSignedCertificate.pfx | Export-Certificate -FilePath MySelfSignedCertificate.cer
    

    Alternatively, you can install and use OpenSSL to convert it from the command line.

    Note 1: As you found, once you set the Authority, the auto-discovery may be able to find the public key from the server.

    Note 2: Rather than store the certificate in a file, you can also store it in the Windows certificate store, and reference it by thumbprint (both PFX and CER files can be imported).

    0 讨论(0)
提交回复
热议问题