Search code examples
c#oauth-2.0jwtauthorizationopeniddict

OpenIddict: How to register signing key in the resource server for validating tokens?


I use OpenIddict. I want to sign the token with the symmetric key. I have configured my authorization server to use OpenIddict. Here is the code in the Startup file.

services.AddOpenIddict()

            .AddServer(options =>
            {
                options.SetTokenEndpointUris("/connect/token");

                options.AllowPasswordFlow()
                       .AllowRefreshTokenFlow();

                options.AcceptAnonymousClients(); 

                options.AddDevelopmentEncryptionCertificate()
                       .AddDevelopmentSigningCertificate()
                       .DisableAccessTokenEncryption();

                options.UseAspNetCore();

                options.RegisterScopes(OpenIddictConstants.Scopes.OfflineAccess);  //This is for grant_type=refresh_token.

                options.EnableDegradedMode();

                options.AddEventHandler<ValidateTokenRequestContext>(c => c.UseSingletonHandler<TokenRequestValidator>());

                options.AddEventHandler<HandleTokenRequestContext>(c => c.UseSingletonHandler<TokenRequestHandler>());

                var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("b14ca5898a4e4133bbce2ea2315a1916")); //this is for example

                options.AddSigningKey(key);
            });

When I receive the token from the authorization server and make calls to the resource server, it responds with 401 Unauthorized.

Here is the code in the resource server's startup file.

 services.AddOpenIddict().AddValidation(options =>
        {

            // Register the ASP.NET Core host.
            options.UseAspNetCore();

            options.UseSystemNetHttp();

            options.SetIssuer("https://localhost:44340/");

        });

Please help me to properly set configurations.


Solution

  • If you want to use a symmetric key for token validation, you'll need to register it in the OpenIddict validation options as symmetric keys are not exposed by the discovery endpoints.

    services.AddOpenIddict()
        .AddValidation(options =>
        {
            options.Configure(o => o.TokenValidationParameters.IssuerSigningKey = key);
        });