Add JWT Security to Web API

Add the package:

Add authentication to the services; configured for JWT:

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.SaveToken = true;
    options.RequireHttpsMetadata = false;
    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidAudience = "https://visual-software.co.uk",
        ValidIssuer = "https://visual-software.co.uk",
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("This is my shared not so secret key"))
    };
});

You will also need Identity configured (before) – see this article.

Add the authorization attribute to your controller classes:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class MyController: ControllerBase
{
   ...

Consumers of your Web API will now have to obtain a JWT and present it in the security header of their requests to access the methods in your controller. Failure to do this will return a ‘401 unauthorized’ response.

Posted in Knowledge Base and tagged , , , .

Leave a Reply

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