In this post, we will walk through the steps to implement JWT (JSON Web Token) authentication in an ASP.NET Core application. JWT is a popular method for securing APIs by ensuring that each request is accompanied by a valid token.
Step-by-Step Guide
Install Required Packages
First, you need to install the necessary NuGet packages. You can do this via the NuGet Package Manager or by running the following command in the Package Manager Console:
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer Install-Package Microsoft.IdentityModel.Tokens
Configure JWT Authentication
In your
Program.cs
orStartup.cs
file, add the following code to configure JWT authentication:using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "yourdomain.com", ValidAudience = "yourdomain.com", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["ApiSettings:Secret"])) }; }); builder.Services.AddControllers(); // Other service configurations var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run();
Add Configuration Settings
Ensure that you have the necessary configuration settings in your
appsettings.json
file:{ "ApiSettings": { "Secret": "your_secret_key_here" } }
Replace
"your_secret_key_here"
with a strong secret key.Protect Your Endpoints
To protect your API endpoints, use the
[Authorize]
attribute in your controllers:using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; [ApiController] [Route("[controller]")] public class SampleController : ControllerBase { [HttpGet] [Authorize] public IActionResult Get() { return Ok("This is a protected endpoint"); } }
Conclusion
By following these steps, you can secure your ASP.NET Core APIs using JWT authentication. This ensures that only requests with valid tokens can access your protected endpoints, enhancing the security of your application.