Search code examples
identityserver4

Certificate for AddSigningCredential


I am new in IdentityServer4 and trying to create JSON Web token. For development I have used AddDeveloperSigningCredential but for other environments I need to use AddSigningCredential but I do not know how to get certificate. I don't have any certificate actually and not sure how can I generate it? Can anyone provide some inputs how to generate certificate and use with AddSigningCredential and then after creation of token, how can I validate token using same certificate in API

After generation of certificate as described in comments. I have added following code

Code in identity server

services.AddIdentityServer() .AddAspNetIdentity() .AddConfigurationStore(options => { options.ConfigureDbContext = builder => builder.UseSqlServer(connectionString, opt => opt.MigrationsAssembly(migrationAssembly)); }) .AddOperationalStore(options => { options.ConfigureDbContext = builder => builder.UseSqlServer(connectionString, opt => opt.MigrationsAssembly(migrationAssembly)); }) .AddSigningCredential(certificate);

Code in API

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.Authority = "localhost:44339"; });

Issuer is

{"issuer":"localhost:44339","jwks_uri":"https://…" I have fetched this information from https://localhost:44339/.well-known/openid-configuration

I am getting 401 error in postman and getting error is WWW-Authenticate: Bearer error="invalid_token", error_description="The audience 'policyservice' is invalid"


Solution

  • You can use any tool that can generate a private/public key pair.

    In the example below I use openssl.

    First we create a RSA private key:

    openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -aes256 -out rsa-private-key.pem
    

    Then you can create a certificate using :

    openssl req -new -x509 -key rsa-private-key.pem -days 365 -subj "/CN=MyRSACert" -out rsa-cert.crt
    

    Then you can package up the cert and private key into a .pfx file:

    openssl pkcs12 -export -inkey rsa-private-key.pem -in rsa-cert.crt -out rsa.pfx
    

    Then in code you can load the cert using:

    var rsaCert = new X509Certificate2("rs256.pfx", "yourpassword");
    

    Then to add it to IdentityServer you can use:

    services.AddIdentityServer()
         ...
        .AddSigningCredential(rsaCert)