[Spring] @RestController 리다이렉트 하기

김동준·2023년 12월 31일

OAuth 2.0을 공부하며 여러가지 시도를 하던 중 OAuth2 서비스를 제공하는 페이지로 리다이렉트를 시켜주어야 했다.

Spring Boot를 사용하여 Controller 클래스를 작성할 때는 항상 @RestController를 사용해 클래스를 작성해왔기 때문에 클라이언트를 리다이렉트 시키는 방법을 잊고 있었으나 검색을 통해 실마리를 찾았다

@RestController를 이용해 Rest API를 제공하는 Controller 클래스에서 사용자를 리다이렉트 시키려면 HttpServletResponse를 파라미터로 받는 메서드를 작성해 HttpResponse 객체를 사용하면 된다.


 @GetMapping("/testTest")
    public ResponseEntity<?> test(@AuthenticationPrincipal PrincipalUser principalUser, HttpServletResponse response) throws IOException {
        System.out.println("test");
        String redirect_uri="http://localhost:8081/login";
        response.sendRedirect(redirect_uri);
        return ResponseEntity.ok().build();
    }

위와 같이 메서드를 작성하게 되면, 사용자가 /testTest 접근하였을 때, spring은 localhost:8081/login 경로로 클라이언트를 리다이렉트 시키게 된다.

profile
더 더 더!

0개의 댓글