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
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:Apply with
[RequireYourKeyHeader]
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")]
).The
.AddApiKey()
method above will require a customAuthenticationHandler<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/