Token-based authentication is a security mechanism that allows users to authenticate themselves and receive a token that can be used to access protected resources. This method is particularly useful for APIs and single-page applications (SPAs) where traditional cookie-based authentication may not be suitable.
How Token-Based Authentication Works
The process of token-based authentication generally involves the following steps:
- The user sends their credentials (username and password) to the server.
- If the credentials are valid, the server generates a token (usually a JSON Web Token, or JWT) and sends it back to the user.
- The user stores the token (typically in local storage or a cookie) and includes it in the Authorization header of subsequent requests.
- The server validates the token on each request to ensure the user is authorized to access the requested resource.
Implementing Token-Based Authentication in ASP.NET Core
To implement token-based authentication in ASP.NET Core, you can use the Microsoft.AspNetCore.Authentication.JwtBearer
package. Below are the steps to set it up:
1. Install Required NuGet Packages
First, you need to install the necessary NuGet package for JWT authentication:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
2. Configure JWT Authentication in Startup.cs
Next, configure JWT authentication in the Startup.cs
file. You will need to specify the token validation parameters, including the issuer, audience, and signing key.
Sample Code for Configuring JWT Authentication
public void ConfigureServices(IServiceCollection services)
{
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 = "YourIssuer",
ValidAudience = "YourAudience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSecretKey"))
};
});
services.AddControllers();
}
3. Creating a Token Generation Method
Next, create a method to generate a JWT token when the user successfully logs in. This method will create claims and sign the token.
Sample Code for Token Generation
public class AuthController : ControllerBase
{
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel model)
{
// Validate user credentials (this is just a placeholder)
if (model.Username == "admin" && model.Password == "password")
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, model.Username),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSecretKey"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "YourIssuer",
audience: "YourAudience",
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token)
});
}
return Unauthorized();
}
}
4. Protecting Routes with Token Authentication
To protect specific routes, you can use the [Authorize]
attribute on controllers or actions. This ensures that only authenticated users with a valid token can access those routes.
Sample Code for Protecting a Route
[Authorize]
[ApiController]
[Route(" api/[controller]")]
public class ProtectedController : ControllerBase
{
[HttpGet]
public IActionResult GetProtectedData()
{
return Ok("This is protected data accessible only with a valid token.");
}
}
5. Testing the Token-Based Authentication
To test the token-based authentication, you can use tools like Postman or curl. First, send a POST request to the login endpoint with valid credentials to receive a token. Then, use that token in the Authorization header for subsequent requests to protected routes.
Sample Request for Login
POST /api/auth/login
Content-Type: application/json
{
"username": "admin",
"password": "password"
}
Sample Request for Protected Route
GET /api/protected
Authorization: Bearer {your_token_here}
Conclusion
Token-based authentication is a powerful and flexible way to secure APIs and applications. By implementing JWT authentication in ASP.NET Core, you can ensure that only authorized users can access protected resources. This method is particularly well-suited for modern web applications and services that require stateless authentication.