Implementing JWT Authentication in .NET Core Web API
Implementing JWT Authentication in .NET Core Web API
JSON Web Token (JWT) is a compact, URL-safe means of representing claims between two parties. In .NET Core, JWT is widely used for securing APIs and implementing stateless authentication. This guide walks you through implementing JWT authentication in your .NET Core Web API.
๐ง Prerequisites
- .NET Core SDK installed
- Basic knowledge of ASP.NET Core & authentication
- A .NET Core Web API project
๐ฆ Step 1: Install Required Package
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
⚙️ Step 2: Configure JWT in Program.cs
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
var key = "your_secret_key_here"; // Use a secure and secret key
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "yourIssuer",
ValidAudience = "yourAudience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key))
};
});
builder.Services.AddAuthorization();
builder.Services.AddControllers();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
๐ Note: Store secrets in appsettings.json or use environment variables — avoid hardcoding keys.
๐ ️ Step 3: Create Authentication Controller
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
[ApiController]
[Route("api/auth")]
public class AuthController : ControllerBase
{
private readonly IConfiguration _config;
public AuthController(IConfiguration config)
{
_config = config;
}
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel login)
{
if (login.Username == "test" && login.Password == "password") // Dummy check
{
var token = GenerateJwtToken(login.Username);
return Ok(new { token });
}
return Unauthorized();
}
private string GenerateJwtToken(string username)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim(ClaimTypes.Name, username)
};
var token = new JwtSecurityToken(
issuer: _config["Jwt:Issuer"],
audience: _config["Jwt:Audience"],
claims: claims,
expires: DateTime.UtcNow.AddHours(1),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
๐ Step 4: Secure API Endpoints
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/secure")]
[Authorize]
public class SecureController : ControllerBase
{
[HttpGet]
public IActionResult GetSecureData()
{
return Ok(new { message = "This is a secure endpoint." });
}
}
๐งช Step 5: Test JWT Authentication
- Run the API
- Send a POST request to
/api/auth/login:{ "username": "test", "password": "password" } - Use the token in Authorization Header:
Authorization: Bearer <YOUR_JWT_TOKEN> - Access the secure endpoint
/api/secure
✅ Conclusion
JWT authentication in .NET Core is a secure, scalable approach for protecting APIs. Remember to:
- Store secrets securely (not hardcoded).
- Use HTTPS in production.
- Implement refresh tokens for long-term authentication.
๐ก Pro Tip: Integrate Swagger UI with JWT Bearer token input for easier testing during development.
Comments
Post a Comment