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!
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.
First, let's create a new ASP.NET Web API project:
dotnet new webapi -n JWTAuthentication
cd JWTAuthenticationTo implement JWT Authentication, we'll use the Microsoft.AspNetCore.Authentication.JwtBearer package:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearerCreate a new file Startup.cs in the App_Start folder and modify it as follows:
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.
Create a new AccountController.cs in the Controllers folder with the following content:
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.
Modify the Login method in AccountController.cs to generate and return a JWT token:
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.
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! 🎯