JWT Authentication in .NET Core 8: A Comprehensive Guide
Guide to implement JWT authentication in .NET Core 8, covering setup, token generation, and secure endpoints.
JWT Authentication in .NET Core 8: A Comprehensive Guide
Guide to implement JWT authentication in .NET Core 8, covering setup, token generation, and secure endpoints.

JWT (JSON Web Token) is widely used for securing APIs due to its stateless nature, which allows token verification without storing session data on the server. It’s efficient and scalable, especially suitable for microservices and RESTful API architectures.

Setting Up JWT Authentication in .NET Core 8

Step 1: Create a New .NET Core 8 API Project

First, create a new API project in .NET Core 8 using the .NET CLI:

Creating a New Project
 
dotnet new webapi -n JwtAuthDemo
cd JwtAuthDemo
            

Step 2: Install Required Packages

For JWT authentication, install the following NuGet packages:

Installing NuGet Packages
 
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package System.IdentityModel.Tokens.Jwt
            

Step 3: Configure JWT Authentication in Program.cs

Next, configure JWT authentication in Program.cs by setting up token validation parameters.

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

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

// Configure JWT Authentication
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 = builder.Configuration["Jwt:Issuer"],
        ValidAudience = builder.Configuration["Jwt:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
    };
});

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

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

app.MapControllers();

app.Run();
            

Step 4: Configure JWT Settings in appsettings.json

Add JWT configurations in appsettings.json for easy access and secure storage:

JWT Settings in appsettings.json
 
{
  "Jwt": {
    "Key": "YourSuperSecretKeyHere",
    "Issuer": "https://yourdomain.com",
    "Audience": "https://yourdomain.com"
  }
}
            

Step 5: Create a Token Generation Method

To issue JWTs, add a method that generates the token based on a user’s credentials.

Generating JWT Tokens
 
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;

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

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSuperSecretKeyHere"));
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

    var token = new JwtSecurityToken(
        issuer: "https://yourdomain.com",
        audience: "https://yourdomain.com",
        claims: claims,
        expires: DateTime.Now.AddMinutes(30),
        signingCredentials: creds);

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

Step 6: Implement Authentication in the Controller

Add a login endpoint to issue tokens upon valid authentication.

Login Endpoint
 
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    [HttpPost("login")]
    public IActionResult Login([FromBody] LoginModel model)
    {
        if (model.Username == "testuser" && model.Password == "password")
        {
            var token = GenerateJwtToken(model.Username);
            return Ok(new { token });
        }
        return Unauthorized();
    }
}

public class LoginModel
{
    public string Username { get; set; }
    public string Password { get; set; }
}
            

Step 7: Secure Your API Endpoints

Apply the [Authorize] attribute to controllers or actions that require authentication.

Securing API Endpoints
 
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class ProtectedController : ControllerBase
{
    [HttpGet]
    public IActionResult GetSecureData()
    {
        return Ok("This is a secure data response.");
    }
}
            

Testing Your API with Swagger

Swagger UI will provide an "Authorize" button, which allows you to input the JWT and test endpoints securely:

  1. Start your app: dotnet run.
  2. Open Swagger by navigating to https://localhost:5001/swagger.
  3. Use the "Authorize" button to enter the JWT token received from the /api/auth/login endpoint.

Conclusion

You’ve successfully implemented JWT authentication in .NET Core 8, creating a secure way to authenticate users. By customizing and expanding upon this setup, you can add role-based access, refresh tokens, and more to make your API security robust and comprehensive.

JWT Authentication .NET Core 8 API Security Token-based Authentication Secure API JSON Web Token Swagger ASP.NET Core
Tejas Bhatt
Tejas Bhatt
Senior Software Enginner
Tejas Bhatt, Senior Software Engineer, excels in .NET Core, Azure, and Angular, crafting scalable apps and sharing insights on coding, cloud, and full-stack dev.

JWT (JSON Web Token) is widely used for securing APIs due to its stateless nature, which allows token verification without storing session data on the server. It’s efficient and scalable, especially suitable for microservices and RESTful API architectures.

Setting Up JWT Authentication in .NET Core 8

Step 1: Create a New .NET Core 8 API Project

First, create a new API project in .NET Core 8 using the .NET CLI:

Creating a New Project
 
dotnet new webapi -n JwtAuthDemo
cd JwtAuthDemo
            

Step 2: Install Required Packages

For JWT authentication, install the following NuGet packages:

Installing NuGet Packages
 
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package System.IdentityModel.Tokens.Jwt
            

Step 3: Configure JWT Authentication in Program.cs

Next, configure JWT authentication in Program.cs by setting up token validation parameters.

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

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

// Configure JWT Authentication
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 = builder.Configuration["Jwt:Issuer"],
        ValidAudience = builder.Configuration["Jwt:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
    };
});

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

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

app.MapControllers();

app.Run();
            

Step 4: Configure JWT Settings in appsettings.json

Add JWT configurations in appsettings.json for easy access and secure storage:

JWT Settings in appsettings.json
 
{
  "Jwt": {
    "Key": "YourSuperSecretKeyHere",
    "Issuer": "https://yourdomain.com",
    "Audience": "https://yourdomain.com"
  }
}
            

Step 5: Create a Token Generation Method

To issue JWTs, add a method that generates the token based on a user’s credentials.

Generating JWT Tokens
 
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;

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

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSuperSecretKeyHere"));
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

    var token = new JwtSecurityToken(
        issuer: "https://yourdomain.com",
        audience: "https://yourdomain.com",
        claims: claims,
        expires: DateTime.Now.AddMinutes(30),
        signingCredentials: creds);

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

Step 6: Implement Authentication in the Controller

Add a login endpoint to issue tokens upon valid authentication.

Login Endpoint
 
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    [HttpPost("login")]
    public IActionResult Login([FromBody] LoginModel model)
    {
        if (model.Username == "testuser" && model.Password == "password")
        {
            var token = GenerateJwtToken(model.Username);
            return Ok(new { token });
        }
        return Unauthorized();
    }
}

public class LoginModel
{
    public string Username { get; set; }
    public string Password { get; set; }
}
            

Step 7: Secure Your API Endpoints

Apply the [Authorize] attribute to controllers or actions that require authentication.

Securing API Endpoints
 
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class ProtectedController : ControllerBase
{
    [HttpGet]
    public IActionResult GetSecureData()
    {
        return Ok("This is a secure data response.");
    }
}
            

Testing Your API with Swagger

Swagger UI will provide an "Authorize" button, which allows you to input the JWT and test endpoints securely:

  1. Start your app: dotnet run.
  2. Open Swagger by navigating to https://localhost:5001/swagger.
  3. Use the "Authorize" button to enter the JWT token received from the /api/auth/login endpoint.

Conclusion

You’ve successfully implemented JWT authentication in .NET Core 8, creating a secure way to authenticate users. By customizing and expanding upon this setup, you can add role-based access, refresh tokens, and more to make your API security robust and comprehensive.

JWT Authentication .NET Core 8 API Security Token-based Authentication Secure API JSON Web Token Swagger ASP.NET Core
Tejas Bhatt
Tejas Bhatt
Senior Software Enginner
Tejas Bhatt, Senior Software Engineer, excels in .NET Core, Azure, and Angular, crafting scalable apps and sharing insights on coding, cloud, and full-stack dev.