아마 이번 포스팅이 JWT 내용을 다루는 마지막 시간일 것 같다.
그렇기에, 자세한 내용에 앞서 JWT 인증 과정에 대해 간단하게 복습하고 넘어가자.
JWT 인증
accessToken
으로 검증이 된 User라면,UserDetails
를 상속받는 Class의 인스턴스를 Spring SecurityContext 내의 인증 정보에 저장하였다.
여기서 스프링 시큐리티
는 SecurityContext
에 인증된 Authentication
객체를 넣어두고 현재 스레드 내에서 공유되도록 관리하는 것이다.
Authentication
인터페이스
보통 UsernamePasswordAuthenticationToken
클래스를 구현체로 사용
필드 : principal
(userId 저장) + credentials
+ authorities
Controller에서 인증정보를 가져오기 위해 @AuthenticationPrincipal 애노테이션
을 사용하면 된다.
앞서 설명했듯이, JWT 인증을 완료한 후 사용자의 정보(userId)는 SecurityContext
의 Authentication
객체의 principal
필드에 저장되어 있다.
그리고 이 정보는 AuthenticationPrincipalArgumentResolver
클래스를 이용해 가져올 수 있다.
AuthenticationPrincipalArgumentResolver 클래스
: 스프링 시큐리티에서
HandlerMethodArgumentResolver
를 구현한 구현체로,@AuthenticationPrincipal
이 실제로 사용되는 부분이다.
- 내부에
resolveArgument()
메소드
SecurityContext
에 저장된 인증객체 기반으로Authentication
객체를 꺼내온다.
(.getPrincipal() -> return principal)
/* 사용자 프로필 반환 API */
/* @AuthenticationPrincipal 애노테이션 사용 -> userId GET */
@GetMapping("/profile")
@ApiOperation(value = "사용자 프로필 조회 API", response = UserProfileResponseDto.class)
public ResponseEntity<SingleResult<UserProfileResponseDto>> findUsersProfile(@AuthenticationPrincipal Long userId) {
UserProfileResponseDto result = userService.findUsersProfile(userId);
return ResponseEntity.ok(responseService.getSingleResult(result));
}
[Spring Security] @AuthenticationPrincipal 어노테이션은 어떻게 동작할까??
위 블로그가 정말 많은 도움이 되었다. 한번 방문해보는 것을 추천한다.