[Spring Security] 복습 + JWT 인증 사용자 정보 가져오기

이수민·2023년 2월 23일
0

spring

목록 보기
9/12

아마 이번 포스팅이 JWT 내용을 다루는 마지막 시간일 것 같다.
그렇기에, 자세한 내용에 앞서 JWT 인증 과정에 대해 간단하게 복습하고 넘어가자.

Spring Security

JWT 인증

accessToken으로 검증이 된 User라면, UserDetails를 상속받는 Class의 인스턴스를 Spring SecurityContext 내의 인증 정보에 저장하였다.

여기서 스프링 시큐리티SecurityContext에 인증된 Authentication 객체를 넣어두고 현재 스레드 내에서 공유되도록 관리하는 것이다.

  • Authentication 인터페이스

    • 보통 UsernamePasswordAuthenticationToken 클래스를 구현체로 사용

    • 필드 : principal(userId 저장) + credentials + authorities


그 덕분에 우리는 이 인증정보를 Controller 단에서 쉽게 꺼내올 수 있다.

@AuthenticationPrincipal 애노테이션

Controller에서 인증정보를 가져오기 위해 @AuthenticationPrincipal 애노테이션을 사용하면 된다.

원리

앞서 설명했듯이, JWT 인증을 완료한 후 사용자의 정보(userId)는 SecurityContextAuthentication 객체의 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 어노테이션은 어떻게 동작할까??
위 블로그가 정말 많은 도움이 되었다. 한번 방문해보는 것을 추천한다.

profile
BE 개발자를 꿈꾸는 학생입니다🐣

0개의 댓글