Add JWT authentication.

Add: JWT authentication in Web API. Related configuration and services are added.
This commit is contained in:
2025-07-10 20:08:48 +08:00
parent 7cce413f79
commit 724b1d4dae
8 changed files with 132 additions and 4 deletions

View File

@ -1,12 +1,16 @@
using System.Text.Json.Serialization;
using OptixServe.Core.Services;
using OptixServe.Api.Dtos;
using OptixServe.Api.Services;
using Microsoft.AspNetCore.Authorization;
namespace OptixServe.Api.Endpoints;
[JsonSerializable(typeof(UserDto))]
[JsonSerializable(typeof(IEnumerable<UserDto>))]
[JsonSerializable(typeof(LoginRequestDto))]
[JsonSerializable(typeof(LoginResponseDto))] // For returning the token string
public partial class UserJsonContext : JsonSerializerContext { }
public static class UserEndpoint
@ -15,8 +19,28 @@ public static class UserEndpoint
{
var group = parentGroup.MapGroup("/users");
group.MapGet("/", GetAllUsers);
group.MapGet("/{id}", GetUserById);
group.MapPost("/login", LoginUser);
group.MapGet("/", GetAllUsers).RequireAuthorization();
group.MapGet("/{id}", GetUserById).RequireAuthorization();
}
public static IResult LoginUser(LoginRequestDto loginRequest, IUserService userService, ITokenService tokenService)
{
if (string.IsNullOrEmpty(loginRequest.UserName) || string.IsNullOrEmpty(loginRequest.Password))
{
return Results.BadRequest("Username and password are required.");
}
// Password hashing and salting will be implemented later.
var user = userService.GetUserByUsername(loginRequest.UserName);
if (user == null || user.Password != loginRequest.Password)
{
return Results.Unauthorized();
}
var token = tokenService.GenerateToken(user);
return Results.Ok(new LoginResponseDto { Token = token });
}
public static IResult GetAllUsers(IUserService userService)
@ -34,4 +58,4 @@ public static class UserEndpoint
return Results.Ok(new UserDto { Id = user.Id, UserName = user.UserName });
}
}
}