Skip to content

Commit c3da532

Browse files
authored
fix: security context에서 꺼내오도록 수정 (#305)
* fix: security context에서 꺼내오도록 수정 * fix: gemini 수정 사항 적용 --------- Co-authored-by: 나용준 <141994188+youngJun99@users.noreply.github.com>
1 parent b1e35e7 commit c3da532

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

src/main/java/ssu/eatssu/global/log/ControllerLogAspect.java

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
import org.aspectj.lang.annotation.Aspect;
1010
import org.aspectj.lang.annotation.Pointcut;
1111
import org.aspectj.lang.reflect.MethodSignature;
12+
import org.springframework.security.core.Authentication;
13+
import org.springframework.security.core.context.SecurityContextHolder;
1214
import org.springframework.security.core.userdetails.UserDetails;
1315
import org.springframework.stereotype.Component;
1416
import org.springframework.web.context.request.RequestContextHolder;
@@ -51,15 +53,7 @@ public Object logApi(ProceedingJoinPoint joinPoint) throws Throwable {
5153
String[] paramNames = methodSignature.getParameterNames();
5254
Object[] args = joinPoint.getArgs();
5355

54-
// 요청자
55-
String userId = IntStream.range(0, args.length)
56-
.filter(i -> args[i] instanceof CustomUserDetails)
57-
.mapToObj(i -> {
58-
CustomUserDetails user = (CustomUserDetails) args[i];
59-
return String.valueOf(user.getId());
60-
})
61-
.findFirst()
62-
.orElse("anonymous");
56+
String userId = getUserIdFromSecurityContext();
6357

6458
String userIdLog = "userId=" + userId;
6559

@@ -127,6 +121,15 @@ private String getCauseMessage(Throwable e) {
127121
return message != null ? message : e.getClass().getSimpleName();
128122
}
129123

124+
private String getUserIdFromSecurityContext() {
125+
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
126+
if (authentication != null && authentication.isAuthenticated() && authentication.getPrincipal() instanceof CustomUserDetails) {
127+
CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
128+
return String.valueOf(userDetails.getId());
129+
}
130+
return "anonymous";
131+
}
132+
130133
private Map<String, Object> toSafeMap(Object arg) {
131134
Map<String, Object> result = new HashMap<>();
132135
for (Field field : arg.getClass().getDeclaredFields()) {

0 commit comments

Comments
 (0)