[SOLVED] How to make jwt bearer token not required in .NET Core 6?

Issue

I have a configuration of JWT Bearer authentication, but sometimes instead of using JWT token, I want to use an API KEY in the request header and check this key in a middleware.

But in that case, when I don’t put the bearer token in the header, I always respond with an Unauthorized response code.

How can I disable the bearer token check?

My configuration:

    services.AddAuthentication(x =>
    {
        x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(options =>
    {
        // options.RequireHttpsMetadata = false;
        // options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            ValidateIssuer = true,
            ValidateAudience = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret)),
            ValidIssuer = jwtSettings.Issuer,
            ValidAudiences = jwtSettings.Audiences,
            ClockSkew = TimeSpan.Zero // remove delay of token when expire
        };
     });

Solution

Rather than checking in a middleware a more idiomatic way you can achieve this by using multipe AuthenticationSchemes. See the MSDN link for more details but at a very high level you can assign add multiple authentication schemes, each with a different scheme. You then refer to this scheme name when using the autorize attribute (e.g. [Authorize(AuthenticationSchemes = "Api-Key-Scheme")]).

services
  .AddAuthentication()
  .AddJwtBearer(options => { .. })
  .AddApiKey(options => { .. });  // custom code

The .AddApiKey() method above will require a custom AuthenticationHandler<T> implementation, an example of how to do that can be found here – https://josef.codes/asp-net-core-protect-your-api-with-api-keys/

Answered By – Fermin

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *