Featured

JWT Authentication In ASP.NET 6

Last modified: May 22, 2022

JWT is one of way to authenticate and authorize user against WEB APIs

1. Create a WEB API project

createproject createproject createproject

2. Remove old code

removecode

3. Install NuGet package

nuget

4. appsettings - setup JWT variables

"Jwt": { "Key": "ertwet3245sgf2342werwergww4352345" }

5. Get token method (in program.cs - above app.Run)

using Microsoft.AspNetCore.Authorization; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; var builder = WebApplication.CreateBuilder(args); // Add services to the container. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.MapPost("/auth/getToken", [AllowAnonymous] (UserDto user) => { /*check if username and password are correct if correct generate JWT token*/ if(user.UserName == "[email protected]" && user.Password == "admin") //you need to check aganist database or identity server { var securityKey = Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]); var handler = new JwtSecurityTokenHandler(); var descriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(JwtRegisteredClaimNames.Name, user.UserName) }), Expires = DateTime.UtcNow.AddMinutes(30), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(securityKey), SecurityAlgorithms.HmacSha256Signature) }; var token = handler.CreateToken(descriptor); var jwtToken = handler.WriteToken(token); return Results.Ok(jwtToken); } else { return Results.Unauthorized(); } }); app.Run(); record UserDto(string UserName, string Password);

5. Test application

Successful

test

Fail

key