OAuth 사용시 postman에서 현재 유저 임의로 설정하기

강다·2022년 11월 18일
0

프로젝트에서 Kakao OAuth를 사용했고, 기존 currentUser(현재 유저)의 경우 카카오로 로그인한 사용자로 고정되어 받아졌다.
그래서, Group이나 Friend부분에서 테스트를 할 때 어려움을 겪었다.
예를들어, friend에서 A가 currentUser라 하고, A→B로 친구 요청을 보내게 되면 currentUser가 B로 바꾸어 친구요청을 수락해야 친구요청 api테스트를 할 수 있지만, 당시로에는 불가능했다.
⇒ 디버깅용 user 서비스를 만들었다.

+currentUser은 userId를 받아 정의 되므로, 간편하게 헤더로 현재유저의 userId(key)의 value를 입력 받을 수 있게 했다.

  • 사용법 : 테스트할 때만 잠시 UserService.java의 @Service 어노테이션을 지우고, UserDebugService.java에다가 @Service를 붙여주면 된다.

헤더로 UserId를 받아 currentUser을 선택해주기 위한


UserDebugService.java

public class UserDebugService extends UserService {
    private final HttpServletRequest request;

    public UserDebugService(UserRepository userRepository, HttpServletRequest request) {
        super(userRepository);
        this.request = request;
    }

    private Integer getUserIdInHeader() {
        String userIdString = request.getHeader("userId");

        if (userIdString == null)
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Unauthorized");
        try {
            return Integer.parseInt(userIdString);
        } catch (NumberFormatException e) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "userID를 파싱할 수 없습니다.");
        }
    }

    @Override
    public User getCurrentUser() {
        return userRepository.getById(getUserIdInHeader());
    }
}
  • UserService를 상속 받으므로 기존 기능은 그대로 사용 가능하다.
  • HttpServletRequest의 getHeader를 사용해 헤더를 통해 userId를 받음
  • 기존 UserService에 있던 getCurrentUser() 함수만 override해서 새로 써줌(헤더에서 받은 아이디 값으로)


💡 super와 this

- super 키워드는 부모 클래스로부터 상속받은 필드나 메소드를 자식 클래스에서 참조하는 데 사용하는 참조 변수
- 인스턴스 변수의 이름과 지역 변수의 이름이 같을 경우 인스턴스 변수 앞에 this 키워드를 사용하여 구분할 수 있음
- 이와 마찬가지로 부모 클래스의 멤버와 자식 클래스의 멤버 이름이 같을 경우 super 키워드를 사용하여 구별할 수 있음
- this() 메소드가 같은 클래스의 다른 생성자를 호출할 때 사용된다면, super() 메소드는 부모 클래스의 생성자를 호출할 
  때 사용됨

사용 예시



기존의 getCurrentUser() 코드

<@Transactional(readOnly = true)
    public User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication == null || authentication.getPrincipal().equals("anonymousUser")) {
            throw new ResponseStatusException(
                    HttpStatus.UNAUTHORIZED, "로그인 되지 않았습니다."
            );
        }

        return (User) authentication.getPrincipal();
    }

0개의 댓글