|
9 | 9 | import org.aspectj.lang.annotation.Aspect; |
10 | 10 | import org.aspectj.lang.annotation.Pointcut; |
11 | 11 | import org.aspectj.lang.reflect.MethodSignature; |
| 12 | +import org.springframework.security.core.Authentication; |
| 13 | +import org.springframework.security.core.context.SecurityContextHolder; |
12 | 14 | import org.springframework.security.core.userdetails.UserDetails; |
13 | 15 | import org.springframework.stereotype.Component; |
14 | 16 | import org.springframework.web.context.request.RequestContextHolder; |
@@ -51,15 +53,7 @@ public Object logApi(ProceedingJoinPoint joinPoint) throws Throwable { |
51 | 53 | String[] paramNames = methodSignature.getParameterNames(); |
52 | 54 | Object[] args = joinPoint.getArgs(); |
53 | 55 |
|
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(); |
63 | 57 |
|
64 | 58 | String userIdLog = "userId=" + userId; |
65 | 59 |
|
@@ -127,6 +121,15 @@ private String getCauseMessage(Throwable e) { |
127 | 121 | return message != null ? message : e.getClass().getSimpleName(); |
128 | 122 | } |
129 | 123 |
|
| 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 | + |
130 | 133 | private Map<String, Object> toSafeMap(Object arg) { |
131 | 134 | Map<String, Object> result = new HashMap<>(); |
132 | 135 | for (Field field : arg.getClass().getDeclaredFields()) { |
|
0 commit comments