.NET 8.0 - Authentication API
Authentication API Sample using JWT Bearer Token in DOT NET 8.0
In the modern landscape of web development, securing APIs is paramount. One of the most robust methods to achieve this is through API authentication using JWT (JSON Web Tokens) as Bearer tokens. This blog post will delve into the what, why, and how of JWT Bearer Token authentication.
JWT, or JSON Web Token, is an open standard (RFC 7519) for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.
A JWT comprises three parts separated by dots (.): Header, Payload, and Signature.
{
"alg": "HS256",
"typ": "JWT"
}
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret
)
Here's a step-by-step explanation of how JWT Bearer Token authentication typically works:
Authorization: Bearer <token>
Let's walk through the JWT token implementation in .NET 8.0 API using the Clean Architecture.
First of all, set up DB and its objects, you can use the scripts shared under the AuthDemo.Infrastructure/Sql
folder of the code sample.
Once our back end is ready, Open Visual Studio 2022 and setup the required projects using the Clean Architecture, if you want to learn more about the Clean Architecture implementation please go through this article.
Set Up Core Layer: Under the solution, create a new Class Library project and name it AuthDemo.Core
.
Entities
and add a new entity class with the name User
.Set Up Application Layer: Add another Class Library Project and name it AuthDemo.Application
.
Core
project.Interfaces
and create a new interface and name it as IUserRepository
.IUnitOfWork
to implement Unit of Work.Set Up Infrastructure Layer: Add a new Class Library Project and name it AuthDemo.Infrastructure
.
Install-Package Dapper
Install-Package Microsoft.Extensions.Configuration
Install-Package Microsoft.Extensions.DependencyInjection.Abstractions
Install-Package System.Data.SqlClient
Application
, and Core
), and add a new folder Repository
.IUserRepository
interface, by creating a new class UserRepository
.IUnitOfWork
interface, by creating a new class UnitOfWork
ServiceCollectionExtension
and add the RegisterServices method under it by injecting IServiceCollection
.Set up API Project: Add a new .NET 8.0 Web API project and name it AuthDemoApi
.
Application
, and Infrastructure
), and add the below packages.
Install-Package Swashbuckle.AspNetCore
Install-Package Microsoft.IdentityModel.Protocols
Install-Package System.IdentityModel.Tokens.Jwt
Install-Package Microsoft.IdentityModel.JsonWebTokens
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer
appsettings.json
file to manage the API settings and replace your DB connection string under the ConnectionStrings
section.
"ConnectionStrings": {
//Update values in the connection string.
"DBConnection": "Data Source=localhost\\SQLEXPRESS; Initial Catalog=AuthDemoDB; Trusted_Connection=True;MultipleActiveResultSets=true"
}
"AppSettings": {
//Replace it with your secret key to verify and sign the JWT tokens, It can be any string.
"Secret": "8c8624e2-2afc-76a5-649e-9b9bf15cf6d3"
}
Configure Startup settings, such as RegisterServices (defined under the AuthDemo.Infrastructure
project), and add the Swagger UI (with Bearer
as the authentication scheme).
Remove the default controller/model classes and add two classes (AuthenticateRequest
and AuthenticateResponse
) under the Model folder, to handle API requests and responses.
Add a Helper
folder and add the below classes.
AppSettings
- to map the the options from appsettings.json
file.AuthorizeAttribute
- to validate the authorization.Common
- Add a GenerateJwtToken method to generate the JWT token.JwtMiddleware
- To validate the token and attach the user to context on successful Jwt validation.Add a new controller and name it UsersController
.
Authenticate
API to validate the user and generate the token.GetAll
API to return all users, and add Authorize
attribute to put it behind the API security.Review the final project structure:
Run the project and test the API methods.
Running API without authentication throws a 401 - Unauthorizeed
error.
Authenticate the user and get a JWT token using the Authenticate
API.
Check the source code here.
Authentication API Sample using JWT Bearer Token in DOT NET 8.0
If you have any comments or suggestions, please leave them behind in the comments section below.