DEV Community

Gaurav
Gaurav

Posted on

6 1

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

👋 One new thing before you go

Tired of spending so much on your side projects? 😒

We have created a membership program that helps cap your costs so you can build and experiment for less. And we currently have early-bird pricing which makes it an even better value! 🐥

We also just added an educational platform to the package!

Substantially upgrade your career earning potential for $8/month ❤️

Top comments (1)

Collapse
 
peter_truchly_4fce0874fd5 profile image
Peter Truchly

This is nice and agile introduction to web tokens. I like the approach of showing how it works (in code), instead of just describing it.
One important note though: It might be a good idea to mention products like Auth0, KeyCloak, AWS Cognito, etc. in a token generation part. These will provide better security and a ton of useful features in a production environment.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay