In this comprehensive tutorial, we will explore how to implement JWT Authentication in ASP.NET Core. JWT (JSON Web Token) is a compact, URL-safe means of representing claims to be transferred between two parties. It is widely used for securing APIs and enabling stateless authentication mechanisms in modern web applications.
JWT stands for JSON Web Token. It is a secure and compact method to transmit identity information between client and server. JWTs are digitally signed, which ensures their integrity and authenticity.
A JWT is composed of three parts separated by dots (.):
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Use the following command to create a new Web API project:
dotnet new webapi -n JwtAuthDemo
Install the following NuGet package to support JWT:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
{
"Jwt": {
"Key": "ThisIsYourSecureKey12345",
"Issuer": "yourdomain.com",
"Audience": "yourdomain.com",
"ExpireMinutes": 60
}
}
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", 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();
app.UseAuthentication();
app.UseAuthorization();
Create a service or controller to generate a JWT upon successful login.
public 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),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token = new JwtSecurityToken(
issuer: _config["Jwt:Issuer"],
audience: _config["Jwt:Audience"],
claims: claims,
expires: DateTime.Now.AddMinutes(Convert.ToDouble(_config["Jwt:ExpireMinutes"])),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel login)
{
if (login.Username == "admin" && login.Password == "admin")
{
var token = GenerateJwtToken(login.Username);
return Ok(new { token });
}
return Unauthorized();
}
Use the [Authorize] attribute to restrict access to authenticated users only.
[Authorize]
[HttpGet("secure-data")]
public IActionResult GetSecureData()
{
return Ok("This is protected data available only to authenticated users.");
}
Claims are key-value pairs included in the token payload to pass user data.
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.Role, "Admin"),
new Claim("Department", "HR")
};
Implementing token refresh logic helps extend sessions without forcing re-login. Typically, you'll issue a short-lived access token and a long-lived refresh token.
JWT authentication in ASP.NET Core provides a modern and secure way of implementing token-based authentication in your web APIs. With the help of middleware and built-in support, .NET developers can quickly set up authentication flows suitable for Single Page Applications (SPAs), mobile apps, and microservices.
By following best practices and security guidelines, JWT can significantly improve both the performance and security of your applications.
Copyrights © 2024 letsupdateskills All rights reserved