Custom Authentication (Validate JWT Token) In .NET Core

Introduction

Custom authentication in .NET Core involves creating a custom authentication handler to validate JWT token (JSON Web Token) tokens. Here’s a step-by-step guide with a code example:

  1. Create a New .NET Core Web API Project:
    Use the following command to create a new .NET Core Web API project:
   dotnet new webapi -n CustomAuthDemo
   cd CustomAuthDemo
  1. Install NuGet Packages:
    Install the necessary NuGet packages for JWT authentication:
   dotnet add package Microsoft.AspNetCore.Authentication
   dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
  1. Configure JWT Authentication:
    In your Startup.cs file, configure JWT authentication in the ConfigureServices method:
   using Microsoft.AspNetCore.Authentication.JwtBearer;
   using Microsoft.IdentityModel.Tokens;

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

       // Configure JWT authentication
       services.AddAuthentication(options =>
       {
           options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
           options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
       }).AddJwtBearer(options =>
       {
           options.TokenValidationParameters = new TokenValidationParameters
           {
               ValidateIssuer = true,
               ValidateAudience = true,
               ValidateIssuerSigningKey = true,
               ValidIssuer = "your-issuer",
               ValidAudience = "your-audience",
               IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"))
           };
       });

       // Add controllers and other services
   }

Replace "your-issuer", "your-audience", and "your-secret-key" with your own values.

  1. Create a Custom Authentication Handler:
    Create a custom authentication handler that will be responsible for validating the JWT token. Create a new class CustomJwtAuthenticationHandler.cs:
   using System.Text.Encodings.Web;
   using System.Threading.Tasks;
   using Microsoft.AspNetCore.Authentication;
   using Microsoft.Extensions.Logging;
   using Microsoft.Extensions.Options;

   public class CustomJwtAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
   {
       public CustomJwtAuthenticationHandler(
           IOptionsMonitor<AuthenticationSchemeOptions> options,
           ILoggerFactory logger,
           UrlEncoder encoder,
           ISystemClock clock)
           : base(options, logger, encoder, clock)
       {
       }

       protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
       {
           // Custom JWT token validation logic
           // Extract the token from the request header and validate it

           // Example: 
           // var token = Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
           // Implement your token validation logic here

           // If token is valid, create a ClaimsPrincipal
           // var claims = new List<Claim>
           // {
           //     new Claim(ClaimTypes.Name, "username")
           // };
           // var identity = new ClaimsIdentity(claims, Scheme.Name);
           // var principal = new ClaimsPrincipal(identity);
           // var ticket = new AuthenticationTicket(principal, Scheme.Name);

           // Return AuthenticateResult.Success(ticket);

           // If token is invalid, return AuthenticateResult.Fail("Invalid token");
       }
   }
  1. Register the Custom Authentication Handler:
    In your Startup.cs file, register the custom authentication handler in the ConfigureServices method:
   using Microsoft.AspNetCore.Authentication;

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

       // Register the custom authentication handler
       services.AddAuthentication("CustomScheme")
           .AddScheme<AuthenticationSchemeOptions, CustomJwtAuthenticationHandler>("CustomScheme", options => { });

       // Add controllers and other services
   }
  1. Apply Authentication to Controllers:
    Apply the Authorize attribute to the controllers or actions that you want to secure using JWT token authentication:
   [Authorize(AuthenticationSchemes = "CustomScheme")]
   [ApiController]
   [Route("api/[controller]")]
   public class SecureController : ControllerBase
   {
       [HttpGet]
       public IActionResult Get()
       {
           return Ok("Authenticated and authorized!");
       }
   }
  1. Run the Application:
    Start the application using the following command:
   dotnet run

You can use tools like curl, Postman, or a browser to test the secured endpoint.

Please note that the example above provides a basic structure for implementing custom JWT token authentication. You’ll need to implement the actual JWT token validation logic in the CustomJwtAuthenticationHandler class based on your authentication provider or logic. Make sure to handle token validation, claims, and principal creation appropriately.

Leave a Reply

Your email address will not be published. Required fields are marked *