In this article we will see how we can add JWT Token authentication to our Minimal API and how we will utilise Swagger to test it out
You can watch the full video on Youtube
Starting Github Repo:
(https://github.com/mohamadlawand087/v52-minimalAPi)
Final Github Rep:
(https://github.com/mohamadlawand087/MinimalApi-JWT)
Once we have pull our application we need to install a nuget package
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
Now that we have completed the initial setup we need to start building our Minimal API
We will be using Swagger to test our MinimalAPI so we will start by updating our Swagger Configuration
var securityScheme = new OpenApiSecurityScheme()
{
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "JSON Web Token based security",
};
var securityReq = new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
};
var contact = new OpenApiContact()
{
Name = "Mohamad Lawand",
Email = "hello@mohamadlawand.com",
Url = new Uri("http://www.mohamadlawand.com")
};
var license = new OpenApiLicense()
{
Name = "Free License",
Url = new Uri("http://www.mohamadlawand.com")
};
var info = new OpenApiInfo()
{
Version = "v1",
Title = "Minimal API - JWT Authentication with Swagger demo",
Description = "Implementing JWT Authentication in Minimal API",
TermsOfService = new Uri("http://www.example.com"),
Contact = contact,
License = license
};
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(o =>
{
o.SwaggerDoc("v1", info);
o.AddSecurityDefinition("Bearer", securityScheme);
o.AddSecurityRequirement(securityReq);
});
After our builder we need to add the following to enable Swagger
app.UseSwagger();
app.UseSwaggerUI();
Once our Swagger is configured, let us now add our JWT configuration.
The first item of our configuration is updating our app settings to the following
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"Jwt": {
"Issuer": "mohamadlawand.com",
"Audience": "mohamadlawand.com",
"Key": "ijurkbdlhmklqacwqzdxmkkhvqowlyqa"
},
"AllowedHosts": "*"