Using JSON Web Tokens (JWT) in .NET Applications
Introduction
JSON Web Tokens (JWT) are a popular method for securely transmitting information between parties as a JSON object. In this tutorial, we will implement JWT authentication in a .NET application.
Setting Up the Project
First, create a new .NET project. You can do this using Visual Studio or the .NET CLI. Here, we'll use the .NET CLI:
dotnet new webapi -n JWTDemo
cd JWTDemo
Installing the Required Packages
Next, install the necessary packages for JWT authentication:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package System.IdentityModel.Tokens.Jwt
Configuring JWT Authentication
Set up JWT authentication in your application. Update the Program.cs
file:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Adding Configuration Settings
Add JWT configuration settings in the appsettings.json
file:
{
"Jwt": {
"Key": "YourSecretKey12345",
"Issuer": "YourIssuer",
"Audience": "YourAudience"
}
}
Generating JWT Tokens
Create a new controller to handle JWT token generation. Add a file named AuthController.cs
:
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace JWTDemo.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
private readonly IConfiguration _configuration;
public AuthController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpPost("token")]
public IActionResult GenerateToken()
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, "your_user_id"),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _configuration["Jwt:Issuer"],
audience: _configuration["Jwt:Audience"],
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token)
});
}
}
}
Securing API Endpoints
Secure your API endpoints by adding the [Authorize]
attribute to your controllers. Update an existing controller or create a new one:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace JWTDemo.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class SecureController : ControllerBase
{
[HttpGet]
public IActionResult GetSecureData()
{
return Ok(new { message = "This is a secure endpoint." });
}
}
}
Testing the Application
Run the application and test the JWT authentication. Use a tool like Postman to generate a token and access the secure endpoint.
// Request to generate a token
POST https://localhost:5001/api/auth/token
// Request to access a secure endpoint with the token
GET https://localhost:5001/api/secure
Authorization: Bearer your_jwt_token_here
Conclusion
In this tutorial, we covered the basics of implementing JWT authentication in a .NET application. We set up a new project, installed the necessary packages, configured JWT authentication, generated JWT tokens, and secured API endpoints. By following these steps, you can implement secure authentication in your own .NET applications using JSON Web Tokens.