JWT (JSON Web Token) is widely used for securing APIs due to its stateless nature, which allows token verification without storing session data on the server. It’s efficient and scalable, especially suitable for microservices and RESTful API architectures.
Setting Up JWT Authentication in .NET Core 8
Step 1: Create a New .NET Core 8 API Project
First, create a new API project in .NET Core 8 using the .NET CLI:
dotnet new webapi -n JwtAuthDemo
cd JwtAuthDemo
Step 2: Install Required Packages
For JWT authentication, install the following NuGet packages:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package System.IdentityModel.Tokens.Jwt
Step 3: Configure JWT Authentication in Program.cs
Next, configure JWT authentication in Program.cs
by setting up token validation parameters.
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
// Configure JWT Authentication
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = 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"]))
};
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Step 4: Configure JWT Settings in appsettings.json
Add JWT configurations in appsettings.json
for easy access and secure storage:
{
"Jwt": {
"Key": "YourSuperSecretKeyHere",
"Issuer": "https://yourdomain.com",
"Audience": "https://yourdomain.com"
}
}
Step 5: Create a Token Generation Method
To issue JWTs, add a method that generates the token based on a user’s credentials.
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
public string GenerateJwtToken(string username)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, username),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSuperSecretKeyHere"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "https://yourdomain.com",
audience: "https://yourdomain.com",
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
Step 6: Implement Authentication in the Controller
Add a login endpoint to issue tokens upon valid authentication.
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel model)
{
if (model.Username == "testuser" && model.Password == "password")
{
var token = GenerateJwtToken(model.Username);
return Ok(new { token });
}
return Unauthorized();
}
}
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
}
Step 7: Secure Your API Endpoints
Apply the [Authorize]
attribute to controllers or actions that require authentication.
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class ProtectedController : ControllerBase
{
[HttpGet]
public IActionResult GetSecureData()
{
return Ok("This is a secure data response.");
}
}
Testing Your API with Swagger
Swagger UI will provide an "Authorize" button, which allows you to input the JWT and test endpoints securely:
- Start your app:
dotnet run
. - Open Swagger by navigating to
https://localhost:5001/swagger
. - Use the "Authorize" button to enter the JWT token received from the
/api/auth/login
endpoint.
Conclusion
You’ve successfully implemented JWT authentication in .NET Core 8, creating a secure way to authenticate users. By customizing and expanding upon this setup, you can add role-based access, refresh tokens, and more to make your API security robust and comprehensive.
JWT (JSON Web Token) is widely used for securing APIs due to its stateless nature, which allows token verification without storing session data on the server. It’s efficient and scalable, especially suitable for microservices and RESTful API architectures.
Setting Up JWT Authentication in .NET Core 8
Step 1: Create a New .NET Core 8 API Project
First, create a new API project in .NET Core 8 using the .NET CLI:
dotnet new webapi -n JwtAuthDemo
cd JwtAuthDemo
Step 2: Install Required Packages
For JWT authentication, install the following NuGet packages:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package System.IdentityModel.Tokens.Jwt
Step 3: Configure JWT Authentication in Program.cs
Next, configure JWT authentication in Program.cs
by setting up token validation parameters.
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
// Configure JWT Authentication
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = 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"]))
};
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Step 4: Configure JWT Settings in appsettings.json
Add JWT configurations in appsettings.json
for easy access and secure storage:
{
"Jwt": {
"Key": "YourSuperSecretKeyHere",
"Issuer": "https://yourdomain.com",
"Audience": "https://yourdomain.com"
}
}
Step 5: Create a Token Generation Method
To issue JWTs, add a method that generates the token based on a user’s credentials.
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
public string GenerateJwtToken(string username)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, username),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSuperSecretKeyHere"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "https://yourdomain.com",
audience: "https://yourdomain.com",
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
Step 6: Implement Authentication in the Controller
Add a login endpoint to issue tokens upon valid authentication.
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel model)
{
if (model.Username == "testuser" && model.Password == "password")
{
var token = GenerateJwtToken(model.Username);
return Ok(new { token });
}
return Unauthorized();
}
}
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
}
Step 7: Secure Your API Endpoints
Apply the [Authorize]
attribute to controllers or actions that require authentication.
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class ProtectedController : ControllerBase
{
[HttpGet]
public IActionResult GetSecureData()
{
return Ok("This is a secure data response.");
}
}
Testing Your API with Swagger
Swagger UI will provide an "Authorize" button, which allows you to input the JWT and test endpoints securely:
- Start your app:
dotnet run
. - Open Swagger by navigating to
https://localhost:5001/swagger
. - Use the "Authorize" button to enter the JWT token received from the
/api/auth/login
endpoint.
Conclusion
You’ve successfully implemented JWT authentication in .NET Core 8, creating a secure way to authenticate users. By customizing and expanding upon this setup, you can add role-based access, refresh tokens, and more to make your API security robust and comprehensive.