-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAuthUserArgumentResolver.java
More file actions
46 lines (37 loc) · 1.96 KB
/
AuthUserArgumentResolver.java
File metadata and controls
46 lines (37 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.example.umc9th.auth.handler;
import com.myApp.auth.annotation.AuthUser;
import com.myApp.global.apiPayload.code.status.AuthErrorCode;
import com.myApp.global.apiPayload.exception.GeneralException;
import org.springframework.core.MethodParameter;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
@Component
public class AuthUserArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(AuthUser.class);
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// 인증 정보가 없거나 익명 사용자인 경우 예외 발생
if (authentication == null || authentication instanceof AnonymousAuthenticationToken
|| !authentication.isAuthenticated()) {
throw new GeneralException(AuthErrorCode.UNAUTHORIZED);
}
Object principal = authentication.getPrincipal();
// Principal이 UserDetails 타입인지 확인
if (!(principal instanceof UserDetails)) {
throw new GeneralException(AuthErrorCode.UNAUTHORIZED);
}
return principal;
}
}