Spring Level 4 ( Controller에서 로그인 사용자 객체 처리 방식의 변화 )

song yuheon·2023년 9월 4일
0

Spring

목록 보기
49/93
post-thumbnail

Spring Security 구성을 적용하며, 로그인 사용자의 객체 처리 방식이 변화해야 한다.


1. 이전 방식:


@PostMapping("/comment")
public CommentResponseDto createComment(@RequestBody CommentRequestDto requestDto, HttpServletRequest req){
    User user = (User) req.getAttribute("user");
    return commentService.createComment(requestDto, user.getUsername());
}

이 방식에서는 HttpServletRequest 객체의 Attribute에서 user 객체를 가져와 사용했다.
하지만 Security Filter의 도입으로 인해 이 방식은 더 이상 사용할 수 없다.


2. 변화된 방식:


@PostMapping("/comment")
public CommentResponseDto createComment(@RequestBody CommentRequestDto requestDto, @AuthenticationPrincipal UserDetailsImpl userDetails){
    User user = (User) userDetails.getUser();
    return commentService.createComment(requestDto, user.getUsername());
}

@AuthenticationPrincipal 어노테이션을 사용하여 현재 인증된 사용자의 UserDetails 객체를 직접 가져온다.
Spring Security의 내장 기능을 활용한 것으로 인증된 사용자의 정보를 Controller에서 쉽게 접근하여 사용 가능하다.

  • principal
    인증된 사용자를 나타낸다. Username/Password 방식의 인증 시 일반적으로 UserDetails 인스턴스를 의미한다.
  • @AuthenticationPrincipal UserDetailsImpl userDetails
    이 구문을 통해 현재 인증된 사용자의 객체에 접근이 가능하다.

3. postman


form 로그인 방식이 아닌 Json객체로 받으니 postman 전송 방식 x-www-form-urlencoded -> raw Json으로 수정


profile
backend_Devloper

0개의 댓글