Logo

dev-resources.site

for different kinds of informations.

Securing Your .NET APIs with JWT Authentication

Published at
1/3/2025
Categories
csharp
jwt
security
dotnet
Author
gaurav-nandankar
Categories
4 categories in total
csharp
open
jwt
open
security
open
dotnet
open
Author
16 person written this
gaurav-nandankar
open
Securing Your .NET APIs with JWT Authentication

JSON Web Tokens (JWT) are a widely-used standard for securing APIs. In this post, we will explore how to implement JWT authentication in a .NET application, including generating tokens, configuring authentication middleware, and enabling Swagger to accept tokens for testing.

1. Prerequisites

Before we begin, ensure your .NET project includes the following:

  • ASP.NET Core
  • NuGet Packages:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package Swashbuckle.AspNetCore
Enter fullscreen mode Exit fullscreen mode

2. Generate JWT Tokens

Add a Login endpoint to generate JWT tokens for authenticated users. Below is the implementation:

public async Task<ActionResult> Login(string email, string password)
{
    var _user = _db.UserMaster.FirstOrDefault(x => x.Email == email && x.Password == password && x.IsDeleted == false);
    if (_user == null)
    {
        return new BadRequestObjectResult("UnAuthorized");
    }

    // JWT Token generation
    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes("sdf5s4f6sd54fsdfsdf"); // Use a secure key and store it safely.
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new Claim[]
        {
            new Claim(ClaimTypes.Name, _user.Id.ToString()),
            new Claim(ClaimTypes.Email, _user.Email)
        }),
        Expires = DateTime.UtcNow.AddHours(1),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
    };

    var token = tokenHandler.CreateToken(tokenDescriptor);
    var tokenString = tokenHandler.WriteToken(token);

    return new OkObjectResult(new
    {
        Token = tokenString,
        ExpiresIn = tokenDescriptor.Expires
    });
}
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • Validate the user credentials (e.g., email and password).
  • Generate a secure JWT token with claims.
  • Return the token to the client.

3. Configure JWT Authentication Middleware

Add JWT authentication middleware in your Program.cs or Startup.cs:

builder.Services.AddAuthentication(Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("sdf5s4f6sd54fsdfsdf")),
            ValidateIssuer = false,
            ValidateAudience = false,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero
        };

        options.Events = new JwtBearerEvents
        {
            OnAuthenticationFailed = context =>
            {
                context.Response.StatusCode = 401;
                context.Response.ContentType = "application/json";
                return context.Response.WriteAsync(JsonConvert.SerializeObject(new { Message = "Authentication Failed" }));
            },
            OnChallenge = context =>
            {
                context.HandleResponse();
                context.Response.StatusCode = 401;
                context.Response.ContentType = "application/json";
                return context.Response.WriteAsync(JsonConvert.SerializeObject(new { Message = "Token is missing or invalid" }));
            }
        };
    });
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • Validate the token's signature, expiration, and audience.
  • Handle authentication errors gracefully.

4. Secure API Endpoints

Use the [Authorize] attribute to secure your endpoints:

[Authorize]
[HttpGet("secure-endpoint")]
public IActionResult SecureEndpoint()
{
    return Ok("This is a secure endpoint!");
}
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • Ensure all sensitive endpoints are protected with [Authorize].
  • Add role-based authorization if needed.

5. Enable Swagger to Accept JWT Tokens

Add Swagger support for JWT authentication:

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API", Version = "v1" });

    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer",
        BearerFormat = "JWT",
        In = ParameterLocation.Header,
        Description = "Enter 'Bearer' [space] and then your token in the text input below.\nExample: \"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9\""
    });

    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            Array.Empty<string>()
        }
    });
});
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • Add a Bearer Token input field in Swagger.
  • Click the Authorize button in Swagger to authenticate.

6. Test the Implementation

  • Generate a token using the Login endpoint.
  • Use Swagger or Postman to send requests to secured endpoints with the token in the Authorization header.

Example Header:

Authorization: Bearer <your_token_here>
Enter fullscreen mode Exit fullscreen mode

7. Conclusion

By following these steps, you have successfully implemented JWT authentication in your .NET application. Your APIs are now secured, and Swagger provides an easy way to test the protected endpoints.

Connect with me:@LinkedIn

jwt Article's
30 articles in total
Favicon
Testing with JWT in .NET APIs
Favicon
JWT Authentication With NodeJS
Favicon
[Part 1] Rails 8 Authentication but with JWT
Favicon
How to Generate a Secure JWT Secret Using Node.js
Favicon
Implementing JWT Authentication in .NET API
Favicon
Managing JWT Logout with Blacklists and Redis: A Beginner-Friendly Guide
Favicon
Understanding the Differences Between OAuth2 and OpenID Connect (OIDC)
Favicon
JWT vs Opaque Tokens: A Comprehensive Guide to Choosing Wisely
Favicon
วิธีทำ Auth API ด้วย Express, JWT, MySQL และ Prisma
Favicon
JsonWebTokenError: jwt must be provided
Favicon
JSON Web Tokens (JWT): Guía Esencial y Buenas Prácticas
Favicon
Djoser+SimpleJWT
Favicon
Mastering JWT Authentication: A Complete Guide with MERN Stack
Favicon
How to secure minimal api microservices with asp.net core identity
Favicon
PHP HyperF -> Firebase JWT
Favicon
How to Create a quick Authentication library for NestJS/MongoDB application
Favicon
Learning JWT security using KumuluzEE — The finances of a league of the environment
Favicon
Feijuca.Auth - Part 1: Configuring the tool
Favicon
Securing Your .NET APIs with JWT Authentication
Favicon
"Unauthorized: No token provided")
Favicon
Implementing JWT Authentication in Express API
Favicon
Integration of Salesforce, Node.js, and React: A Step-by-Step Guide
Favicon
Definition of Jwt and Use
Favicon
Implementing JWT Authentication in Go API
Favicon
flow design for access and refresh token- JWT
Favicon
Implementing JWT Authentication in Spring Boot API
Favicon
What is REST Api ? Implement and Secure ?
Favicon
Securing a REST API with JWT Authentication in C# Using AES-Encrypted Keys
Favicon
MS Graph API Certificate and Client Secret OAuth2.0 in Java Spring boot
Favicon
Securing Your Fullstack App: Authentication & Authorization with JWT in Next.js and Node 🔒 🚀

Featured ones: