JWT Authentication Flow in ASP.NET

beginner
22 min

JWT Authentication Flow in ASP.NET

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!

What is JWT (JSON Web Tokens)? 📝

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.

Why Use JWT? 💡

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.

Setting Up a New ASP.NET Project 🎯

Before we dive into the authentication flow, let's set up a new ASP.NET project.

  1. Install the required NuGet packages: Install-Package Microsoft.AspNetCore.Authentication.JwtBearer Install-Package Microsoft.EntityFrameworkCore.SqlServer

Creating the User Model 📝

csharp
public class ApplicationUser : IdentityUser { public string FirstName { get; set; } public string LastName { get; set; } }

Implementing JWT Authentication 🎯

Now, let's implement JWT authentication in our application.

  1. Configure JWT authentication in Startup.cs:
csharp
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(); }

Creating a Token Service 📝

csharp
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); } }

Authenticating Users 🎯

Now that we have our token service, let's create a method for authenticating users.

csharp
[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 }); }

Adding Authorization 📝

Finally, let's add authorization to our API controllers.

csharp
[Authorize] public class WeatherController : ControllerBase { // Your controller logic here }

Quiz 💡

Quick Quiz
Question 1 of 1

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!