Skip to content

Commit bf41f0f

Browse files
committed
feat: 웹소캣 세션 연결 방법 변경
세션 UserId를 붙여주는 방식으로 변경
1 parent d69d9f6 commit bf41f0f

File tree

28 files changed

+594
-466
lines changed

28 files changed

+594
-466
lines changed

ProjectVG.Api/Controllers/AuthController.cs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
using Microsoft.AspNetCore.Mvc;
22
using ProjectVG.Application.Services.Auth;
3-
using ProjectVG.Common.Constants;
4-
using ProjectVG.Common.Exceptions;
53

64
namespace ProjectVG.Api.Controllers
75
{

ProjectVG.Api/Controllers/ChatController.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
1-
using ProjectVG.Application.Models.API.Request;
2-
using ProjectVG.Application.Services.Chat;
31
using Microsoft.AspNetCore.Mvc;
42
using Microsoft.AspNetCore.Authorization;
5-
using ProjectVG.Api.Filters;
63
using ProjectVG.Application.Models.Chat;
4+
using ProjectVG.Application.Models.API.Request;
5+
using ProjectVG.Application.Services.Chat;
76
using System.Security.Claims;
87

98
namespace ProjectVG.Api.Controllers
109
{
1110
[ApiController]
1211
[Route("api/v1/chat")]
13-
[AllowAnonymous]
1412
public class ChatController : ControllerBase
1513
{
1614
private readonly IChatService _chatService;

ProjectVG.Api/Controllers/OAuthController.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
using Microsoft.AspNetCore.Mvc;
2-
using ProjectVG.Application.Services.Auth;
32
using Microsoft.Extensions.Options;
3+
using ProjectVG.Application.Services.Auth;
44
using ProjectVG.Common.Configuration;
5-
using ProjectVG.Common.Exceptions;
6-
using ProjectVG.Common.Constants;
75

86
namespace ProjectVG.Api.Controllers
97
{

ProjectVG.Api/Controllers/TestController.cs

Lines changed: 0 additions & 60 deletions
This file was deleted.

ProjectVG.Api/Filters/JwtAuthenticationFilter.cs

Lines changed: 13 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
using Microsoft.AspNetCore.Mvc;
21
using Microsoft.AspNetCore.Mvc.Filters;
3-
using Microsoft.Extensions.Logging;
42
using ProjectVG.Infrastructure.Auth;
53
using System.Security.Claims;
64

@@ -13,90 +11,33 @@ public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
1311
{
1412
var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<JwtAuthenticationAttribute>>();
1513
var tokenService = context.HttpContext.RequestServices.GetRequiredService<ITokenService>();
16-
17-
// 디버그: 모든 헤더 로깅
18-
logger.LogInformation("=== JWT 인증 디버그 시작 ===");
19-
logger.LogInformation("요청 경로: {Path}", context.HttpContext.Request.Path);
20-
logger.LogInformation("요청 메서드: {Method}", context.HttpContext.Request.Method);
21-
logger.LogInformation("원격 IP: {RemoteIP}", context.HttpContext.Connection.RemoteIpAddress);
22-
23-
// 모든 헤더 로깅
24-
foreach (var header in context.HttpContext.Request.Headers)
25-
{
26-
logger.LogInformation("헤더: {Key} = {Value}", header.Key, header.Value);
27-
}
28-
29-
var token = ExtractTokenFromHeader(context.HttpContext.Request, logger);
30-
if (string.IsNullOrEmpty(token))
31-
{
32-
logger.LogWarning("인증 헤더가 없거나 유효하지 않음");
33-
context.Result = new UnauthorizedObjectResult(new
34-
{
35-
success = false,
36-
message = "Authorization header is missing or invalid",
37-
debug = new
38-
{
39-
headers = context.HttpContext.Request.Headers.ToDictionary(h => h.Key, h => h.Value.ToString()),
40-
hasAuthorization = context.HttpContext.Request.Headers.ContainsKey("Authorization"),
41-
authorizationValue = context.HttpContext.Request.Headers["Authorization"].FirstOrDefault()
42-
}
43-
});
44-
return;
45-
}
4614

47-
logger.LogInformation("토큰 추출 성공. 토큰 길이: {TokenLength}", token.Length);
48-
logger.LogInformation("토큰 미리보기: {TokenPreview}", token.Length > 20 ? token.Substring(0, 20) + "..." : token);
15+
var token = ExtractToken(context.HttpContext.Request);
16+
if (string.IsNullOrEmpty(token)) {
17+
throw new AuthenticationException(ErrorCode.TOKEN_MISSING);
18+
}
4919

50-
var isValid = await tokenService.ValidateAccessTokenAsync(token);
51-
logger.LogInformation("토큰 검증 결과: {IsValid}", isValid);
52-
53-
if (!isValid)
54-
{
55-
logger.LogWarning("토큰 검증 실패");
56-
context.Result = new UnauthorizedObjectResult(new
57-
{
58-
success = false,
59-
message = "Invalid or expired access token",
60-
debug = new
61-
{
62-
tokenLength = token.Length,
63-
tokenPreview = token.Length > 20 ? token.Substring(0, 20) + "..." : token
64-
}
65-
});
66-
return;
20+
if (!await tokenService.ValidateAccessTokenAsync(token)) {
21+
throw new AuthenticationException(ErrorCode.TOKEN_INVALID);
6722
}
6823

6924
var userId = await tokenService.GetUserIdFromTokenAsync(token);
70-
logger.LogInformation("추출된 사용자 ID: {UserId}", userId);
71-
72-
if (!userId.HasValue)
73-
{
74-
logger.LogWarning("토큰에서 사용자 ID를 추출할 수 없음");
75-
context.Result = new UnauthorizedObjectResult(new
76-
{
77-
success = false,
78-
message = "Unable to extract user information from token"
79-
});
80-
return;
25+
if (!userId.HasValue) {
26+
throw new AuthenticationException(ErrorCode.AUTHENTICATION_FAILED);
8127
}
8228

83-
// ClaimsPrincipal 생성하여 HttpContext에 설정
8429
var claims = new List<Claim>
8530
{
8631
new Claim(ClaimTypes.NameIdentifier, userId.Value.ToString()),
8732
new Claim("user_id", userId.Value.ToString())
8833
};
8934

90-
var identity = new ClaimsIdentity(claims, "Bearer");
91-
var principal = new ClaimsPrincipal(identity);
92-
93-
context.HttpContext.User = principal;
35+
context.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(claims, "Bearer"));
9436
logger.LogInformation("JWT 인증 성공 - 사용자: {UserId}", userId.Value);
9537
}
9638

97-
private string? ExtractTokenFromHeader(HttpRequest request, ILogger logger)
39+
private string? ExtractToken(HttpRequest request)
9840
{
99-
// Nginx 관련 헤더들도 확인
10041
var possibleHeaders = new[]
10142
{
10243
"Authorization",
@@ -105,22 +46,13 @@ public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
10546
"HTTP_AUTHORIZATION"
10647
};
10748

108-
foreach (var headerName in possibleHeaders)
109-
{
49+
foreach (var headerName in possibleHeaders) {
11050
var headerValue = request.Headers[headerName].FirstOrDefault();
111-
logger.LogInformation("헤더 확인 중 '{HeaderName}': {HeaderValue}", headerName, headerValue);
112-
113-
if (!string.IsNullOrEmpty(headerValue) && headerValue.StartsWith("Bearer "))
114-
{
115-
var token = headerValue.Substring("Bearer ".Length);
116-
logger.LogInformation("헤더 '{HeaderName}'에서 토큰 발견: {TokenLength} 문자", headerName, token.Length);
117-
return token;
51+
if (!string.IsNullOrEmpty(headerValue) && headerValue.StartsWith("Bearer ")) {
52+
return headerValue.Substring("Bearer ".Length).Trim();
11853
}
11954
}
12055

121-
// Authorization 헤더가 없거나 Bearer로 시작하지 않는 경우
122-
var authHeader = request.Headers["Authorization"].FirstOrDefault();
123-
logger.LogWarning("유효한 Authorization 헤더를 찾을 수 없음. 원본 Authorization: {AuthHeader}", authHeader);
12456
return null;
12557
}
12658
}

ProjectVG.Api/GlobalUsings.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
11
global using ProjectVG.Common.Constants;
22
global using ProjectVG.Common.Exceptions;
3-
global using ProjectVG.Common.Extensions;
4-
global using ProjectVG.Common.Models;
3+
global using ProjectVG.Api.Filters;

ProjectVG.Api/Middleware/GlobalExceptionHandler.cs

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
using System.Net;
22
using System.Text.Json;
3+
using ProjectVG.Common.Exceptions;
4+
using ProjectVG.Common.Models;
35
using Microsoft.EntityFrameworkCore;
46

57
namespace ProjectVG.Api.Middleware
@@ -46,14 +48,18 @@ private async Task HandleExceptionAsync(HttpContext context, Exception exception
4648

4749
private ErrorResponse CreateErrorResponse(Exception exception, HttpContext context)
4850
{
49-
if (exception is ProjectVG.Common.Exceptions.ValidationException validationEx) {
51+
if (exception is ValidationException validationEx) {
5052
return HandleValidationException(validationEx, context);
5153
}
5254

5355
if (exception is NotFoundException notFoundEx) {
5456
return HandleNotFoundException(notFoundEx, context);
5557
}
5658

59+
if (exception is AuthenticationException authEx) {
60+
return HandleAuthenticationException(authEx, context);
61+
}
62+
5763
if (exception is ProjectVGException projectVGEx) {
5864
return HandleProjectVGException(projectVGEx, context);
5965
}
@@ -122,6 +128,19 @@ private ErrorResponse HandleNotFoundException(NotFoundException exception, HttpC
122128
};
123129
}
124130

131+
private ErrorResponse HandleAuthenticationException(AuthenticationException exception, HttpContext context)
132+
{
133+
_logger.LogWarning(exception, "인증 실패: {ErrorCode} - {Message}", exception.ErrorCode.ToString(), exception.Message);
134+
135+
return new ErrorResponse {
136+
ErrorCode = exception.ErrorCode.ToString(),
137+
Message = exception.Message,
138+
StatusCode = exception.StatusCode,
139+
Timestamp = DateTime.UtcNow,
140+
TraceId = context.TraceIdentifier
141+
};
142+
}
143+
125144
private ErrorResponse HandleProjectVGException(ProjectVGException exception, HttpContext context)
126145
{
127146
_logger.LogWarning(exception, "ProjectVG 예외 발생: {ErrorCode} - {Message}", exception.ErrorCode.ToString(), exception.Message);

0 commit comments

Comments
 (0)