Files
caliverse_server/BrokerApiServer/Common/RequireUserJwtAuthAttribute.cs
2025-05-01 07:23:28 +09:00

28 lines
1.2 KiB
C#

using Microsoft.AspNetCore.Mvc.Filters;
using BrokerApiCore;
namespace BrokerApiServer;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class RequireUserJwtAuthAttribute : System.Attribute, IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var user_auth_service = context.HttpContext.RequestServices.GetRequiredService<UserAuthService>();
Guard.Against.isNull(user_auth_service, ServerErrorCode.InternalServerError, ()=>"PlanetService가 di에 등록돼 있지 않음");
var auth_header = context.HttpContext.Request.Headers.Authorization.FirstOrDefault() ?? string.Empty;
Guard.Against.isNullOrEmptyOrWhiteSpace(auth_header, ServerErrorCode.InvalidUserJwt, ()=>"empty jwt");
Guard.Against.isFalse(auth_header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase),
ServerErrorCode.InvalidUserJwt, ()=>"인증 토큰 오류");
// "Bearer " 이후의 토큰 부분을 추출합니다.
var token = auth_header["Bearer ".Length..].Trim();
var result = await user_auth_service.authByWebPortalToken(token);
Guard.Against.resultFail(result);
context.HttpContext.Items["user_guid"] = user_auth_service.UserGuid;
await next();
}
}