Implementing JWT Authentication in ASP.NET Core
What is a JWT Token?
A JSON Web Token (JWT) is a widely used standard (RFC 7519) for securely transmitting information as a JSON object. JWTs are digitally signed, making them both verifiable and trustworthy.
JWTs can be signed using:
-
HMAC (Hash-based Message Authentication Code)
-
RSA or ECDSA (Asymmetric cryptographic algorithms)
JWTs are commonly used for authentication and authorization in web applications, allowing secure API access without requiring session storage.
Using JWT Authentication in ASP.NET Core Web API
Step 1: Install Required Packages
Ensure you have the required NuGet package installed:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
Step 2: Configure JWT Authentication
Modify Program.cs
to configure authentication using JWT.
Example Configuration:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// Define a secure key
var key = Encoding.UTF8.GetBytes("your_secret_key_here");
builder.Services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options => {
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters {
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "your_issuer",
ValidAudience = "your_audience",
IssuerSigningKey = new SymmetricSecurityKey(key)
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Step 3: Generate JWT Token in a Controller
Create an API endpoint that generates a JWT token upon successful login.
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
[Route("api/auth")]
[ApiController]
public class AuthController : ControllerBase {
[HttpPost("login")]
public IActionResult Login([FromBody] UserLoginModel model) {
// Dummy user validation
if (model.Username != "admin" || model.Password != "password") {
return Unauthorized("Invalid credentials");
}
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes("your_secret_key_here");
var tokenDescriptor = new SecurityTokenDescriptor {
Subject = new ClaimsIdentity(new Claim[] {
new Claim(ClaimTypes.Name, model.Username),
new Claim(ClaimTypes.Role, "Admin") // Add roles if needed
}),
Expires = DateTime.UtcNow.AddHours(1),
Issuer = "your_issuer",
Audience = "your_audience",
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return Ok(new { Token = tokenHandler.WriteToken(token) });
}
}
public class UserLoginModel {
public string Username { get; set; }
public string Password { get; set; }
}
Step 4: Secure API Endpoints Using JWT
Now, protect your API endpoints by requiring authentication.
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[Route("api/secure")]
[ApiController]
[Authorize]
public class SecureController : ControllerBase {
[HttpGet("data")]
public IActionResult GetSecureData() {
return Ok(new { Message = "This is a secure endpoint!" });
}
}
Step 5: Testing JWT Authentication
Obtain a JWT Token
Send a POST request to /api/auth/login
with the following JSON payload:
{
"username": "admin",
"password": "password"
}
Use the JWT Token
When calling a protected API endpoint, pass the token in the Authorization header:
Authorization: Bearer <your_jwt_token>
Conclusion
By implementing JWT authentication in ASP.NET Core, you can securely authenticate users and protect API endpoints. JWT provides a scalable, stateless authentication mechanism, making it a popular choice for modern web applications.
Do you have any questions or need further guidance? Feel free to ask in the comments!
Comments (0)