JWT Token Authentication in C#: A Beginner’s Guide with Code Snippets

DotNet Full Stack Dev
2 min readDec 25, 2023

--

Authentication is a critical aspect of securing applications, and JSON Web Token (JWT) has become a popular choice for implementing secure authentication mechanisms.

In this blog post, we’ll explore JWT token authentication in C#, providing code snippets and explanations to demystify this crucial concept.

Whether you’re a fresher or a developer looking to enhance your authentication knowledge, let’s embark on a journey to understand JWT in the context of C#.

Embark on a journey of continuous learning and exploration with DotNet-FullStack-Dev. https://dotnet-fullstack-dev.blogspot.com/

Background: Understanding JWT

JSON Web Tokens (JWT) are compact, URL-safe means of representing claims between two parties. These claims are typically used to identify the user and provide additional information such as roles and permissions.

JWTs consist of three parts: Header, Payload, and Signature. The Header and Payload are Base64Url encoded JSON strings, and the Signature is used to verify the authenticity of the token.

1. Setting Up a C# Project

Before diving into JWT authentication, let’s set up a simple C# project using ASP.NET Core, a popular framework for building web applications.

dotnet new webapi -n JwtAuthDemo
cd JwtAuthDemo

This creates a basic ASP.NET Core Web API project.

2. Installing Required Packages

To work with JWT in C#, we need the System.IdentityModel.Tokens.Jwt package. Install it using the following command

dotnet add package System.IdentityModel.Tokens.Jwt

3. Configuring Authentication Middleware

In the Startup.cs file, configure the authentication middleware in the ConfigureServices method

public void ConfigureServices(IServiceCollection services)
{
// Other configurations

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 = "your_issuer",
ValidAudience = "your_audience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"))
};
});

// Other configurations
}

Replace "your_issuer", "your_audience", and "your_secret_key" with your specific values.

4. Generating JWT Tokens

Now, let’s create a simple controller to generate JWT tokens.

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
[HttpPost("login")]
public IActionResult Login()
{
var token = GenerateJwtToken();
return Ok(new { token });
}

private string GenerateJwtToken()
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(
issuer: "your_issuer",
audience: "your_audience",
claims: new List<Claim>(),
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);

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

This controller has an endpoint (/api/auth/login) that generates a JWT token using the provided secret key.

5. Protecting Endpoints with JWT

Now, let’s protect an endpoint using JWT authentication.

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class DataController : ControllerBase
{
[HttpGet]
public IActionResult GetData()
{
// Your protected data retrieval logic here
return Ok(new { message = "Protected data retrieved successfully!" });
}
}

The [Authorize] attribute ensures that only requests with valid JWT tokens can access the GetData endpoint.

Conclusion: Securing Your Application with JWT

Understanding JWT token authentication is crucial for building secure and reliable applications. By following the steps outlined in this blog post, you’ve set up a simple ASP.NET Core project, configured JWT authentication middleware, generated JWT tokens, and protected an endpoint.

As you continue your journey in C# development, keep exploring and building upon this foundation to create robust and secure applications.

Happy coding!

--

--

DotNet Full Stack Dev
DotNet Full Stack Dev

Written by DotNet Full Stack Dev

Join me to master .NET Full Stack Development & boost your skills by 1% daily with insights, examples, and techniques! https://dotnet-fullstack-dev.blogspot.com

No responses yet