'How to make jwt bearer token not required in .NET Core 6?

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 1:[1]

You can use the [AllowAnonymous] attribute on your method to disable the authentication check.

Then, create an ActionFilterAttribute and apply it to the same method:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace YourNameSpace
{
    public class RequireYourKeyHeader : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if(!filterContext.HttpContext.Request.Headers.TryGetValue("YourKey", out string headerValue))
            {
                filterContext.Result = new BadRequestObjectResult("missing headr value");
            }
            
            // TODO: check if value passed in the header is actually valid
        }
    }
}

Apply with [RequireYourKeyHeader]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 citronas