Add JWT authentication.
Add: JWT authentication in Web API. Related configuration and services are added.
This commit is contained in:
@ -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 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user