PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, September 2, 2022

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

 September 02, 2022     asp.net, asp.net-core, authentication, jwt     No comments   

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 - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing