Creating a JWT (JSON Web Token) in a .NET Core Web API often entails utilizing the System.Utilisation of the IdentityModel.Tokens.Jwt NuGet package and the configuration of requisite services and settings.

 

Nuget Package
Microsoft.AspNetCore.Authentication.JwtBearer

 

Configuration
configure JWT generating options such secret key, issuer, audience, and expiration time in appsettings.json or appsettings.Development.json.

// appsettings.json
{
 "Jwt": {
   "Key": "CecretKeyHere", // Replace with a strong, unique key
   "Issuer": "yourdomain.com",    // The entity that issues the token (your API).
   "Audience": "yourclientapp.com",    // The entity that will consume the token (your client application).
   "ExpirationInMinutes": 60  // How long the token will be valid.
 }
}

 

Register Services in Program.cs (or Startup.cs for earlier.NET versions): 

  • Get JWT set up Bearer authentication allows you to define the criteria for validating incoming JWTs. 
  • If you want authorization based on roles or claims, you can add authorization policies as an optional component.

 

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

 

// Configure JWT authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
   .AddJwtBearer(options =>
   {
       options.TokenValidationParameters = new TokenValidationParameters
       {
           ValidateIssuer = true,
           ValidateAudience = true,
           ValidateLifetime = true,
           ValidateIssuerSigningKey = true,
           ValidIssuer = builder.Configuration["Jwt:Issuer"],
           ValidAudience = builder.Configuration["Jwt:Audience"],
           IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!))
       };
   });

 

// Add authorization policies (optional)
builder.Services.AddAuthorization();

var app = builder.Build();

 

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
   app.UseSwagger();
   app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthentication(); // Enable authentication middleware
app.UseAuthorization();  // Enable authorization middleware

app.MapControllers();

app.Run();


Generating the JWT Token: 
Add logic in Auth Controller while login

 

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

 

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
   private readonly IConfiguration _configuration;

   public AuthController(IConfiguration configuration)
   {
       _configuration = configuration;
   }

 

   [HttpPost("login")]
   public IActionResult Login([FromBody] UserLogin model)   {
       

        // 1. Authenticate the user (e.g., against a database)
       if (!AuthenticateUser(model.Username, model.Password, out var user))       {
           return Unauthorized("Invalid credentials");
       }

 

       // 2. Generate the JWT token
       var token = GenerateJwtToken(user);

 

       // 3. Return the token to the client
       return Ok(new { Token = token });
   }

 

   private bool AuthenticateUser(string? username, string? password, out UserDto? user)   {       
       if (username == "testuser" && password == "password")   {
           user = new UserDto { Id = 1, Username = username };
           return true;
       }

       user = null;
       return Unauthorized();
   }

 

private string GenerateJwtToken(UserDto user)   {
       var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]!));
       var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

       var claims = new List<Claim>
       {
           new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
           new Claim(ClaimTypes.Name, user.Username!),
           new Claim(ClaimTypes.Role, "User") // Example role
           // Add other claims as needed (e.g., email, permissions)
       };

       var token = new JwtSecurityToken(
           issuer: _configuration["Jwt:Issuer"],
           audience: _configuration["Jwt:Audience"],
           claims: claims,
           expires: DateTime.Now.AddMinutes(int.Parse(_configuration["Jwt:ExpirationInMinutes"]!)),
           signingCredentials: credentials);

       return new JwtSecurityTokenHandler().WriteToken(token);
   }
}

 

DTOs / Models

public class UserLogin{
   public string? Username { get; set; }
   public string? Password { get; set; }
}

public class UserDto  {
   public int Id { get; set; }
   public string? Username { get; set; }
   // Add other user properties
}

 

 

 

 

 


Related Question