Previous Dependency Injection in NET core Securing an ASP.NET Core Web API Next

All about JWT, its Structure and Signature and Validation

What is JWT Token?

A JWT (JSON Web Token) is a compact, URL-safe token used to securely transmit information between parties as a JSON object. It is commonly used for authentication and authorization in web applications.

Structure of a JWT

A JWT consists of three parts separated by dots:

header.payload.signature

1. Header

Contains metadata about the token, such as the signing algorithm.

{
  "alg": "HS256",
  "typ": "JWT"
}  

2. Payload

Contains the claims or user data.

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true,
  "exp": 1700000000
}  

3. Signature

Used to verify that the token was not tampered with.

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secretKey
)
  

Example Token

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiJ1c2VyMTIzIiwibmFtZSI6IkpvaG4gRG9lIiwicm9sZSI6IkFkbWluIiwiZXhwIjoxNzAwMDAwMDAwfQ.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c  

Why Use JWT?

  • Stateless authentication
  • Compact and easy to transmit
  • Secure with digital signatures
  • Works across different platforms

Common Use Cases

  • User login and session management
  • API authorization
  • Single Sign-On (SSO)

JWT Token in .NET Core

Information Needed to Generate JWT

  • Secret Key: A secure string used to sign the token.
  • Issuer: Identifies who issued the token.
  • Audience: Identifies who the token is intended for.
  • Claims: Key-value pairs that carry user data (e.g., username, roles).
  • Expiration Time: Defines how long the token is valid.
  • Signing Algorithm: Usually HMAC SHA256.

Steps to Generate JWT Token in .NET Core

1. Install Package

Run the following command to install the JWT library:

dotnet add package System.IdentityModel.Tokens.Jwt

2. Configure appsettings.json

"Jwt": {
  "Key": "YourSuperSecretKeyHere",
  "Issuer": "YourAppName",
  "Audience": "YourAppUsers",
  "ExpireMinutes": 60
}
  

3. Create Token Generator

using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;

public class JwtTokenGenerator
{
    private readonly IConfiguration _config;

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

    public string GenerateToken(string username)
    {
        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, username),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            issuer: _config["Jwt:Issuer"],
            audience: _config["Jwt:Audience"],
            claims: claims,
            expires: DateTime.Now.AddMinutes(Convert.ToDouble(_config["Jwt:ExpireMinutes"])),
            signingCredentials: creds
        );

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

4. Use in Controller

[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel model)
{
    if (model.Username == "admin" && model.Password == "password")
    {
        var token = _jwtTokenGenerator.GenerateToken(model.Username);
        return Ok(new { token });
    }

    return Unauthorized();
}
  

Summary

  • Install the JWT package
  • Configure your secret key and settings
  • Create a method to generate the token
  • Return the token from your login endpoint

Implementing JWT Authentication in .NET Core Web API

1. Install Required Package

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

2. Configure appsettings.json

"Jwt": {
  "Key": "YourSuperSecretKeyHere",
  "Issuer": "YourAppName",
  "Audience": "YourAppUsers",
  "ExpireMinutes": 60
}
  

3. Add Authentication in Program.cs or Startup.cs

builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", 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"]))
        };
    });
  

4. Generate JWT Token

public string GenerateToken(string username)
{
    var claims = new[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, username),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
    };

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

    var token = new JwtSecurityToken(
        issuer: _config["Jwt:Issuer"],
        audience: _config["Jwt:Audience"],
        claims: claims,
        expires: DateTime.Now.AddMinutes(Convert.ToDouble(_config["Jwt:ExpireMinutes"])),
        signingCredentials: creds
    );

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

5. Create Login Endpoint

[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel model)
{
    if (model.Username == "admin" && model.Password == "password")
    {
        var token = _jwtTokenGenerator.GenerateToken(model.Username);
        return Ok(new { token });
    }

    return Unauthorized();
}
  

6. Protect API Endpoints

[Authorize]
[HttpGet("secure-data")]
public IActionResult GetSecureData()
{
    return Ok("This is protected data.");
}
  

Summary

  • Install JWT packages
  • Configure settings and authentication
  • Generate and return token on login
  • Use [Authorize] to protect endpoints
Back to Index
Previous Dependency Injection in NET core Securing an ASP.NET Core Web API Next
*