.NET - JWT Authentication

JWT Authentication in ASP.NET Core (.NET) - Complete Guide

JWT Authentication in ASP.NET Core

In this comprehensive tutorial, we will explore how to implement JWT Authentication in ASP.NET Core. JWT (JSON Web Token) is a compact, URL-safe means of representing claims to be transferred between two parties. It is widely used for securing APIs and enabling stateless authentication mechanisms in modern web applications.

What is JWT?

JWT stands for JSON Web Token. It is a secure and compact method to transmit identity information between client and server. JWTs are digitally signed, which ensures their integrity and authenticity.

Structure of a JWT

A JWT is composed of three parts separated by dots (.):

  • Header
  • Payload
  • Signature

Example JWT

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Why Use JWT in ASP.NET Core?

  • Stateless authentication (no session on server)
  • Cross-platform (mobile, web, API consumers)
  • Secure and compact
  • Decouples the frontend and backend

Setting Up JWT Authentication in ASP.NET Core

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

Use the following command to create a new Web API project:

dotnet new webapi -n JwtAuthDemo

Step 2: Install Required NuGet Packages

Install the following NuGet package to support JWT:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Step 3: Configure JWT Settings in appsettings.json

{
  "Jwt": {
    "Key": "ThisIsYourSecureKey12345",
    "Issuer": "yourdomain.com",
    "Audience": "yourdomain.com",
    "ExpireMinutes": 60
  }
}

Step 4: Configure Authentication in Program.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"]))
        };
    });

Step 5: Enable Authentication and Authorization Middleware

var app = builder.Build();

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

Creating JWT Token

Token Generation Logic

Create a service or controller to generate a JWT upon successful login.

public string GenerateJwtToken(string username)
{
    var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
    var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

    var claims = new[]
    {
        new Claim(ClaimTypes.Name, username),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
    };

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

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

Login Endpoint

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

    return Unauthorized();
}

Protecting API Endpoints

Use the [Authorize] attribute to restrict access to authenticated users only.

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

Customizing Token Claims

Claims are key-value pairs included in the token payload to pass user data.

var claims = new List<Claim>
{
    new Claim(ClaimTypes.Name, username),
    new Claim(ClaimTypes.Role, "Admin"),
    new Claim("Department", "HR")
};

Validating JWT in Postman

  1. Login using your POST endpoint and get the token.
  2. Copy the token and go to your protected GET endpoint.
  3. In Postman, add the token to the Authorization tab:
    • Type: Bearer Token
    • Token: <your_jwt_token>

Refreshing Tokens (Optional)

Implementing token refresh logic helps extend sessions without forcing re-login. Typically, you'll issue a short-lived access token and a long-lived refresh token.

Best Practices for JWT Authentication

  • Always use HTTPS to transmit tokens.
  • Keep token expiration short (e.g., 15-60 minutes).
  • Use refresh tokens for prolonged sessions.
  • Store JWT securely on client-side (e.g., HttpOnly cookies).
  • Revoke tokens on logout or password change.

Common JWT Authentication Errors

  • Invalid signature: Mismatched key or token tampering.
  • Token expired: Token lifetime has passed.
  • 401 Unauthorized: Missing or invalid token in request.


JWT authentication in ASP.NET Core provides a modern and secure way of implementing token-based authentication in your web APIs. With the help of middleware and built-in support, .NET developers can quickly set up authentication flows suitable for Single Page Applications (SPAs), mobile apps, and microservices.

By following best practices and security guidelines, JWT can significantly improve both the performance and security of your applications.

Beginner 5 Hours
JWT Authentication in ASP.NET Core (.NET) - Complete Guide

JWT Authentication in ASP.NET Core

In this comprehensive tutorial, we will explore how to implement JWT Authentication in ASP.NET Core. JWT (JSON Web Token) is a compact, URL-safe means of representing claims to be transferred between two parties. It is widely used for securing APIs and enabling stateless authentication mechanisms in modern web applications.

What is JWT?

JWT stands for JSON Web Token. It is a secure and compact method to transmit identity information between client and server. JWTs are digitally signed, which ensures their integrity and authenticity.

Structure of a JWT

A JWT is composed of three parts separated by dots (.):

  • Header
  • Payload
  • Signature

Example JWT

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ. SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Why Use JWT in ASP.NET Core?

  • Stateless authentication (no session on server)
  • Cross-platform (mobile, web, API consumers)
  • Secure and compact
  • Decouples the frontend and backend

Setting Up JWT Authentication in ASP.NET Core

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

Use the following command to create a new Web API project:

dotnet new webapi -n JwtAuthDemo

Step 2: Install Required NuGet Packages

Install the following NuGet package to support JWT:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Step 3: Configure JWT Settings in appsettings.json

{ "Jwt": { "Key": "ThisIsYourSecureKey12345", "Issuer": "yourdomain.com", "Audience": "yourdomain.com", "ExpireMinutes": 60 } }

Step 4: Configure Authentication in Program.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"])) }; });

Step 5: Enable Authentication and Authorization Middleware

var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization();

Creating JWT Token

Token Generation Logic

Create a service or controller to generate a JWT upon successful login.

public string GenerateJwtToken(string username) { var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(ClaimTypes.Name, username), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; var token = new JwtSecurityToken( issuer: _config["Jwt:Issuer"], audience: _config["Jwt:Audience"], claims: claims, expires: DateTime.Now.AddMinutes(Convert.ToDouble(_config["Jwt:ExpireMinutes"])), signingCredentials: credentials ); return new JwtSecurityTokenHandler().WriteToken(token); }

Login Endpoint

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

Protecting API Endpoints

Use the [Authorize] attribute to restrict access to authenticated users only.

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

Customizing Token Claims

Claims are key-value pairs included in the token payload to pass user data.

var claims = new List<Claim> { new Claim(ClaimTypes.Name, username), new Claim(ClaimTypes.Role, "Admin"), new Claim("Department", "HR") };

Validating JWT in Postman

  1. Login using your POST endpoint and get the token.
  2. Copy the token and go to your protected GET endpoint.
  3. In Postman, add the token to the Authorization tab:
    • Type: Bearer Token
    • Token: <your_jwt_token>

Refreshing Tokens (Optional)

Implementing token refresh logic helps extend sessions without forcing re-login. Typically, you'll issue a short-lived access token and a long-lived refresh token.

Best Practices for JWT Authentication

  • Always use HTTPS to transmit tokens.
  • Keep token expiration short (e.g., 15-60 minutes).
  • Use refresh tokens for prolonged sessions.
  • Store JWT securely on client-side (e.g., HttpOnly cookies).
  • Revoke tokens on logout or password change.

Common JWT Authentication Errors

  • Invalid signature: Mismatched key or token tampering.
  • Token expired: Token lifetime has passed.
  • 401 Unauthorized: Missing or invalid token in request.


JWT authentication in ASP.NET Core provides a modern and secure way of implementing token-based authentication in your web APIs. With the help of middleware and built-in support, .NET developers can quickly set up authentication flows suitable for Single Page Applications (SPAs), mobile apps, and microservices.

By following best practices and security guidelines, JWT can significantly improve both the performance and security of your applications.

Related Tutorials

Frequently Asked Questions for General

line

Copyrights © 2024 letsupdateskills All rights reserved