Introduction
In this article, we'll cover how we can create and configure JWT Bearer Authentication and Authorization for APIs built with .Net 5.0. There are plenty of resources out which cover "JWT Auth" but in this article, we'll be focusing on the implementation of custom JWT Authentication with Custom JWT middleware and a custom authorize attribute.
JWT Authentication
![]()
Prerequisites
- Visual Studio 2019 - Download from here
- .Net 5.0 SDK - Download from here
Topics to be covered
- Setup the .Net 5.0 Web API Project.
- Configure JWT Authentication
- Generate JWT Token.
- Validate JWT Token using Custom Middleware and Custom Authorize Attribute.
- Testing the Endpoint (API) with Swagger.
Setup the .Net 5.0 Web API project
Open Visual Studio and select "Create a new project" and click the "Next" button.
![]()
Add the "project name" and "solution name" also the choose the path to save the project in that location, click on "Next".
![]()
Now choose the target framework ".Net 5.0" which we get once we install the SDK and also will get one more option to configure Open API support by default with that check box option.
![]()
Configure JWT Authentication
To configure the JWT(JSON web tokens) we must have the Nuget package installed inside the project, so let's first add the project dependencies.
NuGet Packages to be installed
Inside the Visual Studio - Click on Tools -> Nuget Package Manager -> Manage Nuget packages for solution.
![]()
Install through Console,
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version 5.0.7
The first step is to configure the JWT authentication in our project. To do this, we need to register a JWT schema inside the swagger service by using the "AddAuthentication" method and specifying by passing the values.
Let's define the Swagger Service and attach the JWT Auth code,
Add Service Authentication to perform the Auth Scheme and its challenge and add the JWTBearer to Authorize the token through the Swagger.
In the above example, we have specified the parameters that must be taken into consideration to validate the token.
- Validate the server (ValidateIssuer = true) that generates the token.
- Validate the recipient of the token is authorized to receive (ValidateAudience = true)
- Check if the token is not expired and the signing key of the issuer is valid (ValidateLifetime = true)
- Validate signature of the token (ValidateIssuerSigningKey = true)
We have to specify the values for "Audience", "Issuer" and "Secret key" in this project we have stored these values inside the appsettings.json file.
appsettings.json
Generate JWT Token
Let's create a controller named AuthController inside the controller folder and add the Auth method which is responsible to validate the login credentials and create the token based on username. We have marked this method with the AllowAnonymous attribute to bypass the authentication. This method expects LoginModel object for username and password.
We have created a service folder in which our core business logic is residing and we are using dependency injection to consume these services in the controller via constructor injection.
For demo purposes, I have hardcoded the values inside the method to validate the model.
UserService.cs
IUserService.cs
Add this service to the Startup class under the configure services method.
services.AddTransient<IUserService,UserService>();
Inside the Auth controller, let us create the private method known as "GenerateJwtToken" to create a token based on the Issuer, Audience, and Secretkey which we defined in the appsettings.json file.
AuthController.cs
Once we enabled the Authentication, I have created a sample Get API by adding the Authorize Attribute So that this API will trigger the validation check of the token passed with an HTTP request.
If someone tries to access this API without the proper token, it will throw a 401 (Unauthorized Access) as a response. If we want to bypass the authentication for any of our existing methods, we can mark that method with the AllowAnonymous attribute.
Validate JWT Token using Custom Middleware and Custom Authorize Attribute
Below is the custom JWT middleware that validates the token in the request "Authorization" header if it exists. On successful validation, the middleware retrieves that associated user from the database and assigns it to its context.Items["User"] makes the current account available to any other code running within the current request scope, which we'll use below in a custom authorization attribute.
Create a folder named Middleware in which will add the JWTMiddleware and AuthorizeAttribute class.
JWTMiddleware.cs
AuthorizeAttribute.cs
Let's inject this Middleware into the Startup class.
So each time whoever hits the API with the Authorization header it will validate the token first and sends the appropriate response in the body.
How did JWTMiddleware work?
If(ValidToken) "Authorized"
else "UnAuthorized"
Testing the API with Swagger (OpenAPI)
Run the application; it will take us to the Swagger index page with all the configuration setup we made in the project.
![]()
Let's pass the valid credentials to the Auth API to get the access token.
![]()
Copy the token and add the same token in the Authorize button followed by Bearer "Token".
![]()
Now all the APIs are Authorized in the Swagger. Let us test the Get API.
![]()
Conclusion
JWT is very famous in web development. It is an open standard that allows transmitting data between parties as a JSON object in a secure and compact way. In this article, we learned how to create and Validate JWT with ASP.NET core application.
Thank you for reading, please let me know your questions, thoughts, or feedback in the comments section. I appreciate your feedback and encouragement.
You can view or download the source code from the GitHub link here.
keep Learning ...!