Advertisement

Advertisement

JWT in ASP.NET Core

JWT in ASP.NET Core

Step 1: Set Up the User Model

Create a user model to define properties like Name, Email, Password, and Role.

public class User

{

    public string Name { get; set; }

    public string Email { get; set; }

    public string Password { get; set; }

    public string Role { get; set; }

}



Step 2: Install JWT Packages

Install the following NuGet packages:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

dotnet add package System.IdentityModel.Tokens.Jwt



Step 3: Configure JWT in Program.cs

Add JWT authentication configuration in the Program.cs file.

using Microsoft.AspNetCore.Authentication.JwtBearer;

using Microsoft.IdentityModel.Tokens;

using System.Text;


var builder = WebApplication.CreateBuilder(args);


// Add JWT Authentication

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

    .AddJwtBearer(options =>

    {

        options.TokenValidationParameters = new TokenValidationParameters

        {

            ValidateIssuer = true,

            ValidateAudience = true,

            ValidateLifetime = true,

            ValidateIssuerSigningKey = true,

            ValidIssuer = "your-issuer",

            ValidAudience = "your-audience",

            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"))

        };

    });


builder.Services.AddAuthorization();

builder.Services.AddControllers();


var app = builder.Build();


app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();


app.Run();



Step 4: Create a Controller for Authentication

Add a Controller File AuthController.cs:

using Microsoft.AspNetCore.Mvc;

using Microsoft.IdentityModel.Tokens;

using System.IdentityModel.Tokens.Jwt;

using System.Security.Claims;

using System.Text;


[ApiController]

[Route("api/[controller]")]

public class AuthController : ControllerBase

{

    private static List<User> Users = new List<User>

    {

        new User { Name = "Admin", Email = "admin@example.com", Password = "admin123", Role = "Admin" },

        new User { Name = "User", Email = "user@example.com", Password = "user123", Role = "User" }

    };


    private const string Key = "your-secret-key"; // Keep this secret


    [HttpPost("login")]

    public IActionResult Login([FromBody] UserLogin userLogin)

    {

        var user = Users.FirstOrDefault(u => u.Email == userLogin.Email && u.Password == userLogin.Password);


        if (user == null)

        {

            return Unauthorized(new { message = "Invalid credentials" });

        }


        var token = GenerateJwtToken(user);

        return Ok(new { token });

    }


    private string GenerateJwtToken(User user)

    {

        var claims = new[]

        {

            new Claim(JwtRegisteredClaimNames.Sub, user.Name),

            new Claim(JwtRegisteredClaimNames.Email, user.Email),

            new Claim(ClaimTypes.Role, user.Role),

            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())

        };


        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Key));

        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);


        var token = new JwtSecurityToken(

            issuer: "your-issuer",

            audience: "your-audience",

            claims: claims,

            expires: DateTime.Now.AddHours(1),

            signingCredentials: creds

        );


        return new JwtSecurityTokenHandler().WriteToken(token);

    }

}


public class UserLogin

{

    public string Email { get; set; }

    public string Password { get; set; }

}



Step 5: Secure Endpoints with Role-based Authorization

Add role-based authorization to your controllers.

Example:

[ApiController]

[Route("api/[controller]")]

public class SecureController : ControllerBase

{

    [HttpGet("admin")]

    [Authorize(Roles = "Admin")]

    public IActionResult AdminEndpoint()

    {

        return Ok(new { message = "Welcome Admin!" });

    }


    [HttpGet("user")]

    [Authorize(Roles = "User")]

    public IActionResult UserEndpoint()

    {

        return Ok(new { message = "Welcome User!" });

    }


    [HttpGet("all")]

    [Authorize]

    public IActionResult AllUsers()

    {

        return Ok(new { message = "Welcome, authenticated user!" });

    }

}



Step 6: Test the API

  1. Use Postman to test the login endpoint:

    • POST: http://localhost:5000/api/auth/login


{

    "email": "admin@example.com",

    "password": "admin123"

}


{

    "token": "your-jwt-token"

}


  1. Use the JWT token in the Authorization header for subsequent requests:

    • Header: Authorization: Bearer your-jwt-token


Summary

  1. Login API generates a JWT token based on the user role.

  2. Secure Endpoints using [Authorize] and [Authorize(Roles = "RoleName")].

  3. Test the API using Postman.

--------------------------------------------------------------------------------------------------------------

1. ValidIssuer

  • Ye wo entity (server) hai jo token ko issue karta hai. Issuer ka address ya naam hota hai, jo token ke andar hote hain.

  • Aap ise apne application ke naam ya domain ke roop me set kar sakte hain.

Example:

  • "your-issuer" ko aap apne application ya server ke naam se replace kar sakte hain. Agar aap localhost pe develop kar rahe hain toh, aap http://localhost:5000 ya apne domain name ka use kar sakte hain.


ValidIssuer = "http://localhost:5000"  // Ya apne server ka URL


2. ValidAudience

  • Audience wo client (user) hai jo token ko consume karega. Ye typically wo application hai jo JWT token ko validate karega.

  • Aap apne app ka naam ya URL yahan set kar sakte hain.

Example:

  • "your-audience" ko aap apne client application ke URL ya identifier se replace kar sakte hain.


ValidAudience = "http://localhost:5000"  // Ya apne client application ka URL


3. IssuerSigningKey

  • Ye wo secret key hai jo JWT token ko sign karne ke liye use hoti hai. Ye key token ko validate karne mein madad karti hai.

  • Aap apni secret key ko securely set karte hain, jo sirf aapke server ko pata hoti hai.

  • Aap yahan koi bhi strong secret key use kar sakte hain. Secret key ko strong rakhna zaroori hai.

Example:

  • "your-secret-key" ko aap apni secret key se replace kar sakte hain.

  • Example ke liye, "mySuperSecretKey123" ya koi aur strong key use kar sakte hain.

IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("mySuperSecretKey123"))


Complete Example:


var tokenValidationParameters = new TokenValidationParameters

{

    ValidIssuer = "http://localhost:5000",  // Token ka issuer

    ValidAudience = "http://localhost:5000",  // Token ko consume karne wala audience

    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("mySuperSecretKey123"))  // Secret signing key

};


Key Points to Remember:

  • Issuer (ValidIssuer): Ye wo identity hai jo JWT token ko issue karta hai (aapka server).

  • Audience (ValidAudience): Ye wo identity hai jo token ko consume karne ka hak rakhta hai (aapka client ya user).

  • Signing Key (IssuerSigningKey): Ye wo secret key hai jisse JWT token sign hota hai, aur token ko verify karne ke liye use hoti hai.

Next Steps:

  1. Replace placeholders:

    • "http://localhost:5000" ko apne actual server ya application URL se replace karein.

    • "mySuperSecretKey123" ko apni strong secret key se replace karein.

  2. Keep the Secret Key Secure:

    • Important: Secret key ko kisi bhi external source ya repository me store na karein. Isse apne application configuration me securely store karein (e.g., environment variables, Azure Key Vault, etc.).

Aapke JWT configuration ab secure hoga aur aap apne application me authentication aur authorization ko effectively handle kar sakenge.




JWT in ASP.NET Core JWT in ASP.NET Core Reviewed by Rikesh on January 02, 2025 Rating: 5

No comments:

Powered by Blogger.