Custom JWT Token In ASP.NET Core Web API

Introduction

Creating a custom JWT token in ASP.NET Core Web API involves generating a JWT (JSON Web Token) with custom claims and using it for authentication and authorization. Here’s a step-by-step example of how you can create a custom JWT token in an ASP.NET Core Web API:

Step 1: Create a new ASP.NET Core Web API Project

Create a new ASP.NET Core Web API project using .NET CLI or Visual Studio.

Step 2: Install Required Packages

In your project, install the necessary NuGet packages for JWT authentication:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Step 3: Configure JWT Authentication

In the Startup.cs file, configure JWT authentication in the ConfigureServices and Configure methods:

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

public class Startup
{
    // ...

    public void ConfigureServices(IServiceCollection services)
    {
        // ...

        var key = Encoding.ASCII.GetBytes("your-secret-key"); // Replace with your secret key
        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(x =>
        {
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });

        // ...
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // ...

        app.UseAuthentication();
        app.UseAuthorization();

        // ...
    }
}

Step 4: Generate Custom JWT Token

Create a controller in your API to generate a custom JWT token with custom claims:

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

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

    public AuthController(IConfiguration config)
    {
        _config = config;
    }

    [AllowAnonymous]
    [HttpPost("token")]
    public IActionResult GenerateToken()
    {
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, "username"),
            new Claim("custom-claim", "value"),
            // Add additional custom claims
        };

        var token = new JwtSecurityToken(
            _config["Jwt:Issuer"],
            _config["Jwt:Issuer"],
            claims,
            expires: DateTime.Now.AddMinutes(30),
            signingCredentials: creds
        );

        return Ok(new
        {
            token = new JwtSecurityTokenHandler().WriteToken(token)
        });
    }
}

Step 5: Configure AppSettings.json

Add the JWT configuration to your appsettings.json file:

"Jwt": {
  "Key": "your-secret-key",
  "Issuer": "your-issuer"
}

Step 6: Test the Custom JWT Token Generation

Run your ASP.NET Core Web API and use a tool like Postman to make a POST request to /api/auth/token. You should receive a response containing the custom JWT token.

This example demonstrates how to generate a custom JWT token in an ASP.NET Core Web API using the JwtBearerDefaults authentication scheme. Custom claims can be added to the JWT token to include additional information about the authenticated user. Remember to replace the secret key and issuer with secure values and handle token expiration and renewal based on your application’s requirements.

Leave a Reply

Your email address will not be published. Required fields are marked *