Welcome to our comprehensive guide on JWT Authentication Flow in ASP.NET! 🎉 This tutorial is designed to be beginner-friendly, yet packed with enough depth for intermediate learners. Let's dive right in!
JSON Web Tokens (JWT) are a compact, URL-safe means of representing claims to enable authentication. They are a standard method for passing information between parties as a JSON object.
JWTs are useful for creating stateless APIs, making it easier to scale applications. They allow you to securely transmit information between parties, such as user identity, without storing sensitive data on the server.
Before we dive into the authentication flow, let's set up a new ASP.NET project.
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer
Install-Package Microsoft.EntityFrameworkCore.SqlServer
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
}Now, let's implement JWT authentication in our application.
Startup.cs:public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key")),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddControllers();
}public class TokenService
{
private readonly IHttpContextAccessor _httpContextAccessor;
public TokenService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public string GenerateToken(ApplicationUser user)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"));
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _httpContextAccessor.HttpContext.RequestServices.GetService<IConfiguration>["Jwt:Issuer"],
audience: _httpContextAccessor.HttpContext.RequestServices.GetService<IConfiguration>["Jwt:Audience"],
claims: claims,
expires: DateTime.UtcNow.AddHours(8),
signingCredentials: signingCredentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}Now that we have our token service, let's create a method for authenticating users.
[HttpPost("authenticate")]
public IActionResult Authenticate([FromBody] ApplicationUser user)
{
var userFromDb = _userManager.Users.FirstOrDefault(u => u.UserName == user.UserName);
if (userFromDb == null || !_userManager.CheckPasswordAsync(userFromDb, user.Password).Result)
{
return BadRequest(new { message = "Invalid username or password" });
}
var token = _tokenService.GenerateToken(userFromDb);
return Ok(new { token = token });
}Finally, let's add authorization to our API controllers.
[Authorize]
public class WeatherController : ControllerBase
{
// Your controller logic here
}What is the purpose of JWT in ASP.NET applications?
That's it for our JWT Authentication Flow tutorial in ASP.NET! We hope you enjoyed learning and found this tutorial helpful. 🎉 Happy coding!