Securing Your .NET APIs with JWT Authentication

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MyrinNew
    Senior Member
    • Feb 2024
    • 5168

    #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







    2. Generate JWT Tokens

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






    public async Task 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
    });
    }







    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.AspNe tCore.Authentication.JwtBearer.JwtBearerDefaults.A uthenticationScheme)
    .AddJwtBearer(options =>
    {
    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationPara meters
    {
    ValidateIssuerSigningKey = true,
    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("sdf5 s4f6sd54fsdfsdf")),
    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.SerializeO bject(new { Message = "Authentication Failed" }));
    },
    OnChallenge = context =>
    {
    context.HandleResponse();
    context.Response.StatusCode = 401;
    context.Response.ContentType = "application/json";
    return context.Response.WriteAsync(JsonConvert.SerializeO bject(new { Message = "Token is missing or invalid" }));
    }
    };
    });







    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!");
    }







    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()
    }
    });
    });







    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







    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




    More...
Working...