skip to Main Content

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
        };
     });

2

Answers


  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 header value");
                }
                
                // TODO: check if value passed in the header is actually valid
            }
        }
    }
    

    Apply with [RequireYourKeyHeader]

    Login or Signup to reply.
  2. 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/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search