Dominic Jordan
Dominic Jordan

Reputation: 43

How does .net core web api jwtbearer middleware verify OpenID Connect token with authentication provider

I have been banging my head against the wall for a few days now. The solution is probably too simple to state in blogs so I ask the question here.

I am developing a .NET Core Web API which should delegate all authentication and authorization to a Keycloak identity provider server.

I have written the following code in my Startup.cs file:

services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            }).AddJwtBearer(o =>
            {
                o.Authority = "https://idp.abc.xyz/auth/realms/master";
                o.Audience = "products-api";
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Administrator", policy => policy.RequireClaim("user_roles", "product_catalog_admin"));
                options.AddPolicy("User", policy => policy.RequireClaim("user_roles", "product_catalog_user"));


            });

Now I can use Postman to request a token from the IDP and send that token to the Web API. Then the Web API validates that token but does NOT know anything about the IDP other than the URL and only makes a request to a public URL of the IDP to get some configuration.

Question: HOW does the Web API know that the token is valid, not tampered with (created using different key), if it doesn't know anything about the IDP?

Upvotes: 3

Views: 2048

Answers (1)

Gary Archer
Gary Archer

Reputation: 29263

AddJwtBearer will use the options you give it to perform in memory validation of tokens. By default this involves the following actions:

  • Validate issuer
  • Validate audience
  • Check that the token's exp claim is not in the past (expired)
  • Verify the access token's digital signature

The 4th check is the most complex and by default this involves downloading token signing public keys from the IDP's JWKS endpoint, then choosing the one in the JWT's kid header. A blog post of mine has some details on how this works.

Of course you should always test the above 4 conditions and ensure that in each case API access is denied with a 401 error response that clients can code against.

Upvotes: 3

Related Questions