chris
chris

Reputation: 4351

Unable to validate RS256 signed JWT

I am trying to implement signed JWT (RS256) on a dotnet webapi along with KeyCloak. On app start I can see the openid calls being made to keycloak with the expected response content (requests shown below).

Get the jwks_url here

GET https://localhost:8080/auth/realms/core/.well-known/openid-configuration

Get the keys from here

GET https://localhost:8080/auth/realms/core/protocol/openid-connect/certs

I then get an access_token with the request below

POST https://localhost:8080/auth/realms/core/protocol/openid-connect/token
Content-Type: application/x-www-form-urlencoded

grant_type=password&client_id=admin-cli&username=jim&password=foobar

I then test out the following endpoint

[ApiController]
[Route("/")]
public class AppController : ControllerBase
{
    [Authorize]
    [HttpGet]
    public OkObjectResult Get()
    {
        return Ok("This is the secured page");
    }
}

with this request

GET https://localhost:5001
Authorization: Bearer MY_TOKEN 

But I always get a 401

HTTP/1.1 401 Unauthorized
Content-Length: 0
Date: Wed, 18 Nov 2020 17:41:28 GMT
Server: Kestrel
Www-Authenticate: Bearer error="invalid_token", error_description="The signature key was not found"

The signature key (third 'chunk') does exist in the token. Below is the JWT validation code. Am I missing something?

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    var audience = Configuration["Jwt:Audience"];
    var issuer = Configuration["Jwt:Issuer"];
    bool.TryParse(Configuration["Jwt:RequireHttpsMetadata"], out var requireHttpsMetadata);

    IConfigurationManager<OpenIdConnectConfiguration> configurationManager =
        new ConfigurationManager<OpenIdConnectConfiguration>(
            $"{Configuration["Jwt:Authority"]}/auth/realms/core/.well-known/openid-configuration",
            new OpenIdConnectConfigurationRetriever());
    var openIdConfig =
        configurationManager.GetConfigurationAsync(CancellationToken.None).Result;

    services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            options.SaveToken = true;
            options.RequireHttpsMetadata = requireHttpsMetadata;
            options.TokenValidationParameters.IssuerSigningKeys = openIdConfig.SigningKeys;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,

                ValidIssuer = issuer,
                ValidAudience = audience,
                ValidateIssuerSigningKey = true,
            };
        });
}

Upvotes: 1

Views: 742

Answers (1)

monty
monty

Reputation: 8755

Since the JWT holds a signature (aka third chunk) I would interpret the message

"The signature key was not found"

that there is a problem with the validation of the signature.

Recheck the responses/accessibility of

GET https://localhost:8080/auth/realms/core/protocol/openid-connect/certs

Upvotes: 1

Related Questions