Monday, May 22, 2023

minimal api authentication JWT .NET 6

 To implement minimal API authentication with JWT (JSON Web Tokens) in .NET 6, you can follow these steps:


Step 1: Create a new .NET 6 Minimal API project.


Step 2: Install the required NuGet packages:


dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

dotnet add package System.IdentityModel.Tokens.Jwt



Step 3: Configure JWT authentication in the `Program.cs` file:


using Microsoft.AspNetCore.Authentication.JwtBearer;

using Microsoft.IdentityModel.Tokens;


var builder = WebApplication.CreateBuilder(args);


// JWT Configuration

var jwtSettings = builder.Configuration.GetSection("JwtSettings");

var key = Encoding.ASCII.GetBytes(jwtSettings["SecretKey"]);

var tokenValidationParameters = new TokenValidationParameters

{

    ValidateIssuerSigningKey = true,

    IssuerSigningKey = new SymmetricSecurityKey(key),

    ValidateIssuer = false,

    ValidateAudience = false

};


builder.Services.AddAuthentication(options =>

{

    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;

    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

})

.AddJwtBearer(options =>

{

    options.TokenValidationParameters = tokenValidationParameters;

});


builder.Services.AddSingleton(tokenValidationParameters);




Step 4: Configure JWT secret key and issuer in the `appsettings.json` file:

{

  "JwtSettings": {

    "SecretKey": "your_secret_key_here"

  }

}



Step 5: Protect your API endpoints with the `[Authorize]` attribute:


using Microsoft.AspNetCore.Authorization;



app.MapGet("/protected", () =>

{

    return "This is a protected endpoint.";

}).RequireAuthorization(); // Requires authentication for this endpoint


Step 6: Generate JWT tokens during the login process:


using System.IdentityModel.Tokens.Jwt;

using Microsoft.Extensions.Configuration;

using Microsoft.IdentityModel.Tokens;



app.MapPost("/login", async (LoginModel model, IConfiguration configuration) =>

{

    // Validate the user credentials and generate JWT token

    if (IsValidUser(model.Username, model.Password))

    {

        var tokenHandler = new JwtSecurityTokenHandler();

        var jwtSettings = configuration.GetSection("JwtSettings");

        var key = Encoding.ASCII.GetBytes(jwtSettings["SecretKey"]);

        var tokenDescriptor = new SecurityTokenDescriptor

        {

            Subject = new ClaimsIdentity(new[]

            {

                new Claim(ClaimTypes.Name, model.Username)

            }),

            Expires = DateTime.UtcNow.AddHours(1),

            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)

        };

        var token = tokenHandler.CreateToken(tokenDescriptor);

        var tokenString = tokenHandler.WriteToken(token);

        return Results.Ok(new { Token = tokenString });

    }

    else

    {

        return Results.Unauthorized();

    }

});



Step 7: Test the protected endpoints by including the JWT token in the `Authorization` header of the request:


GET /protected HTTP/1.1

Host: localhost:5000

Authorization: Bearer <your_token_here>



That's it! With these steps, you have implemented minimal API authentication with JWT in .NET 6 using the Minimal API approach. Remember to customize the authentication and authorization logic according to your requirements.

No comments:

Post a Comment

ASP.NET Core

 Certainly! Here are 10 advanced .NET Core interview questions covering various topics: 1. **ASP.NET Core Middleware Pipeline**: Explain the...