- 내정보 조회 API 구현 — @AuthenticationPrincipal
- Authentication 인터페이스 구현체에서 principal 필드를 추출하는 어노테이션
- JwtAuthenticationToken 타입이 사용되었다면 JwtAuthentication 객체를 의미함
- 적절한 권한 (USER 또는 ADMIN)이 없다면 스프링 시큐리티 인가 처리 과정에서 예외가 발생하고, 내정보 조회 API 자체가 호출되지 않음
- 따라서, 내정보 조회 API 가 정상 호출되는 상황에서 JwtAuthentication 객체가
null
상태인 경우는 없음
JwtAuthentication authentication = (JwtAuthentication) SecurityContextHolder.getContext().getAuthentication().getPrincipal()
HandlerMethodArgumentResolver
Controller 메소드 호출에 필요한 파리미터를 바인딩 시키기 위한 인터페이스이다. 좀 더 세부적으로는 supportsParameter 메소드가 true를 반환하는 경우 resolveArgument 메소드가 실행되어 Controller 메소드 호출에 필요한 파라미터를 만들게 된다.
@RestController @RequestMapping("/api") public class UserRestController { private final UserService userService; private final AuthenticationManager authenticationManager; public UserRestController(UserService userService, AuthenticationManager authenticationManager) { this.userService = userService; this.authenticationManager = authenticationManager; } @GetMapping(path = "/user/me") public UserDto me(@AuthenticationPrincipal JwtAuthentication authentication) { return userService.findByLoginId(authentication.username) .map(user -> new UserDto(authentication.token, authentication.username, user.getGroup().getName()) ) .orElseThrow(() -> new IllegalArgumentException("Could not found user for " + authentication.username)); } @PostMapping(path = "/user/login") public UserDto login(@RequestBody LoginRequest request) { JwtAuthenticationToken authToken = new JwtAuthenticationToken(request.getPrincipal(), request.getCredentials()); Authentication resultToken = authenticationManager.authenticate(authToken); JwtAuthentication authentication = (JwtAuthentication) resultToken.getPrincipal(); User user = (User) resultToken.getDetails(); return new UserDto(authentication.token, authentication.username, user.getGroup().getName()); } }