Peter M
Peter M

Reputation: 472

Customize WWW-Authenticate challenge header with Jwt Bearer Authentication middleware in WebAPI

I'm using the JwtBearerAuthentication Katana middleware in a .NET WebAPI project to secure my web API via JWT.

So, in my Startup class I'm just doing something simple like:

 app.UseJwtBearerAuthentication(
            new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                AllowedAudiences = new[] { audience },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                }
            });

Everything works great, with one exception.

When a client passes in an invalid or missing Bearer token the WWW-Authenticate response header is just "Bearer".

I'd like to customize that header to include the address of my authorization server and the supported grant types.

Something more like: WWW-Authenticate: MyAuth href=url,grant_type="supported-grants" or whatever...

What is the best way to do this? I'm surprised the JwtBearerAuthenticationOptions class does not include a Challenge property. I can work around this, but wanted to know if there is a best practice here with the Jwt middleware or not.

Upvotes: 2

Views: 4335

Answers (1)

Peter M
Peter M

Reputation: 472

We ended up inserting the WWW-Authenticate header with the values we wanted using OnApplyChallenge within the OAuthBearerAuthenticationProvider.

Something along the lines of:

app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions ...
   Provider = new OAuthBearerAuthenticationProvider()....
      OnApplyChallenge = (context) => context.OwinContext.Response.Headers.AppendValue(WWWAuthenticateHeader,values)

Upvotes: 2

Related Questions