JWT Token Creation, Authentication And Authorization In ASP.NET Core 6.0 With Postman

Introduction

So, the process of creating, authenticating, and authorizing JWT tokens in ASP.NET Core 6.0 using Postman for testing. JWT (JSON Web Tokens) are a popular way to secure web applications by providing a digitally signed token that can carry claims about the user.

Here’s a step-by-step guide:

Step 1: Create a New ASP.NET Core 6.0 Web API Project

  1. Create a new ASP.NET Core Web API project using your preferred development environment (Visual Studio, Visual Studio Code, etc.).
  2. Configure your authentication and authorization settings in the Startup.cs file. Add the necessary NuGet packages if they’re not already included:
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Text;
public void ConfigureServices(IServiceCollection services)
{
    // ... other configurations

    // Add JWT authentication
    var key = Encoding.ASCII.GetBytes("YourSecretKey"); // Replace with your secret key
    services.AddAuthentication(x =>
    {
        x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(x =>
    {
        x.RequireHttpsMetadata = false;
        x.SaveToken = true;
        x.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false
        };
    });

    // ... other configurations
}

Step 2: Create Token Generation Endpoint

  1. Add a new controller in your project and create an endpoint for generating JWT tokens:
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    private readonly IConfiguration _config;

    public AuthController(IConfiguration config)
    {
        _config = config;
    }

    [HttpPost("login")]
    public IActionResult Login()
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes("YourSecretKey"); // Replace with your secret key
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.Name, "YourUsername") // Replace with user information
            }),
            Expires = DateTime.UtcNow.AddHours(1), // Set token expiration time
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);
        var tokenString = tokenHandler.WriteToken(token);

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

Step 3: Test with Postman

  1. Launch Postman.
  2. Create a new request and set the request type to POST.
  3. Set the request URL to your token generation endpoint, for example: https://localhost:5001/api/auth/login (replace with your actual URL).
  4. Click on the “Headers” tab and add a new key-value pair: Content-Type -> application/json.
  5. Click on the “Body” tab and select “raw”, then enter an empty JSON object {}.
  6. Send the request. You should receive a response containing a JWT token.

Step 4: Secure Your API Endpoints

  1. Add an [Authorize] attribute to the controllers or actions that you want to secure with JWT authentication.
  2. Test your secured endpoints by including the JWT token in the Authorization header of your Postman requests. Set the header like this:
   Authorization: Bearer <your-token>

Remember, this is a simplified example for demonstration purposes. In a real-world scenario, you would typically store the secret key and user data securely, validate user credentials, and possibly integrate with a database for user management.

Leave a Reply

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