How to Implement JWT Token Authentication in .NET Core 6

Vinod Pal
5 min readSep 3, 2023

--

Authentication is a crucial aspect of web application security. It ensures that users are who they claim to be before granting them access to specific resources or functionalities. One popular method of authentication in modern web development is JSON Web Tokens (JWT). In this article, we will explore how to implement JWT token authentication in a .NET Core 6 application.

Photo by Amirr Zolfaqari on Unsplash

Why JWT Authentication?

JWT is a compact, URL-safe means of representing claims to be transferred between two parties. These claims can be digitally signed, making it a secure way to authenticate and transmit information between the client and server. JWT tokens are often used for:

  1. Stateless Authentication: JWTs are self-contained and can store user information, reducing the need for server-side storage or session management.
  2. Cross-Origin Authentication: They can be easily used in single-page applications (SPAs) and mobile apps due to their compact format.
  3. Scalability: JWTs can be easily distributed and validated across multiple servers, making them ideal for microservices architectures.

Now, let’s dive into the steps to implement JWT token authentication in a .NET Core 6 application.

Step 1: Create a .NET Core 6 Web API Project

Start by creating a new .NET Core 6 Web API project in your preferred development environment. You can use Visual Studio or the .NET CLI. Once the project is created, you can proceed with the following steps.

This is what our basic API controller appears like. Its sole purpose is to provide the response “Hello World”

using Microsoft.AspNetCore.Mvc;

namespace JwtInDotnetCore.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class HelloWorldController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok("Hello World");
}
}
}

After running the application we can hit the endpoint using postman and we see 200 response.

Step 2: Install Required NuGet Packages

You’ll need some NuGet packages to handle JWT authentication. Open your project’s .csproj file and add the following package references:

<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.15.0" />

Save the changes and restore the packages.

You can also install these packages using Nuget UI or dotnet CLI.

Step 3: Configure JWT Authentication

In appsettings.json add JWT token details.

 "Jwt": {
"Key": "YourSecretKeyForAuthenticationOfApplication",
"Issuer": "youtCompanyIssuer.com"
}

In your Program.cs file, configure JWT authentication

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

//Jwt configuration starts here
var jwtIssuer = builder.Configuration.GetSection("Jwt:Issuer").Get<string>();
var jwtKey = builder.Configuration.GetSection("Jwt:Key").Get<string>();

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtIssuer,
ValidAudience = jwtIssuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey))
};
});
//Jwt configuration ends here

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();


app.MapControllers();

app.Run();

Step 4: Generate JWT Tokens

We will create JWT tokens when a user logs in.

We are creating another controller for login activities

using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;

namespace JwtInDotnetCore.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class LoginController : ControllerBase
{
private IConfiguration _config;
public LoginController(IConfiguration config)
{
_config = config;
}

[HttpPost]
public IActionResult Post([FromBody] LoginRequest loginRequest)
{
//your logic for login process
//If login usrename and password are correct then proceed to generate token

var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

var Sectoken = new JwtSecurityToken(_config["Jwt:Issuer"],
_config["Jwt:Issuer"],
null,
expires: DateTime.Now.AddMinutes(120),
signingCredentials: credentials);

var token = new JwtSecurityTokenHandler().WriteToken(Sectoken);

return Ok(token);
}
}
}

Step 5: Protect API Endpoints

Now that you have configured JWT authentication, you can protect your API endpoints by applying the [Authorize] attribute to controllers or actions that require authentication.

[Authorize]
[Route("api/[controller]")]
[ApiController]
public class HelloWorldController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok("Hello World");
}
}

Since now we have added [Authorize] in the controller, when we call HelloWorld endpoint we get an 401 response.

It means we are not authorized to access this endpoint without valid token. So lets generate a new token.

Now we can call login API to get the token which we can use for authentication

As you can see after successful login we get a valid token returned.

We will now add this token inside the request header Authorization with value as Bearer new_token

Now as you can see after adding token we get a success response.

Congratulations, you have now protected your API with JWT authentication

Source code is available here:

Conclusion

Implementing JWT token authentication in a .NET Core 6 application is a powerful way to secure your APIs. It allows you to create stateless, scalable, and cross-origin authentication systems, making it ideal for modern web development. By following the steps outlined in this article, you can enhance the security of your application and protect your valuable resources effectively.

And that’s a wrap! If you’ve read this far, it means you liked this article. If that’s true, please leave a clap. I publish similar articles every week, so feel free to follow me for more.

--

--

Vinod Pal

Just your friendly neighborhood full-stack developer. Building awesome applications, one line of code at a time.