JWT Authentication in ASP.NET Tutorial 🎯

beginner
16 min

JWT Authentication in ASP.NET Tutorial 🎯

Welcome to our comprehensive guide on JWT Authentication in ASP.NET! This tutorial is designed to help both beginners and intermediates understand and implement JWT (JSON Web Tokens) for secure authentication in ASP.NET applications. Let's dive in!

Understanding JWT Authentication 📝

JWT is a compact, URL-safe means of representing claims to be transferred between two parties. In our case, we'll use it to authenticate users in ASP.NET applications.

Why use JWT Authentication?

  • Stateless: No need to maintain user sessions on the server
  • Standardized: Adheres to the OAuth 2.0 and OpenID Connect standards
  • Flexible: Contains all necessary claims for authentication and authorization

Setting up a new ASP.NET project 💡

First, let's create a new ASP.NET Web API project:

sh
dotnet new webapi -n JWTAuthentication cd JWTAuthentication

Installing required packages 💡

To implement JWT Authentication, we'll use the Microsoft.AspNetCore.Authentication.JwtBearer package:

sh
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Configuring JWT Authentication 💡

Create a new file Startup.cs in the App_Start folder and modify it as follows:

csharp
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; // ... public void ConfigureServices(IServiceCollection services) { services.AddIdentity<IdentityUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.SaveToken = true; options.RequireHttpsMetadata = false; options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key")), ValidateIssuer = false, ValidateAudience = false }; }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }

💡 Pro Tip: Replace "your-secret-key" with a secure secret key for your application.

Creating a user registration and login API 💡

Create a new AccountController.cs in the Controllers folder with the following content:

csharp
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using System.Security.Claims; using System.Text; using System.Threading.Tasks; // ... [Route("api/[controller]")] [ApiController] public class AccountController : ControllerBase { private readonly UserManager<IdentityUser> _userManager; public AccountController(UserManager<IdentityUser> userManager) { _userManager = userManager; } [HttpPost("register")] public async Task<ActionResult<IdentityUser>> Register(RegisterModel model) { // ... } [HttpPost("login")] public async Task<ActionResult<UserViewModel>> Login(LoginModel model) { // ... } } public class RegisterModel { // ... } public class LoginModel { public string Username { get; set; } public string Password { get; set; } } public class UserViewModel { public string Username { get; set; } public string Token { get; set; } }

💡 Pro Tip: Add the necessary models and database context for user registration and login.

Generating JWT tokens 💡

Modify the Login method in AccountController.cs to generate and return a JWT token:

csharp
public async Task<ActionResult<UserViewModel>> Login(LoginModel model) { var user = await _userManager.FindByNameAsync(model.Username); if (user == null || await _userManager.CheckPasswordAsync(user, model.Password)) { return BadRequest("Invalid username or password"); } var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; var token = await _tokenGenerator.CreateTokenAsync(claims); return Ok(new UserViewModel { Username = user.UserName, Token = new JwtSecurityTokenHandler().WriteToken(token) }); }

💡 Pro Tip: Inject IJwtFactory to generate the JWT token.

Quiz 📝

Quick Quiz
Question 1 of 1

Which package is used to implement JWT Authentication in ASP.NET?

That's it for this tutorial on JWT Authentication in ASP.NET! Now you have the knowledge and code examples to implement secure authentication in your own ASP.NET applications. Stay tuned for more tutorials on CodeYourCraft! 🎯