Back-end/Spring

[Spring] 무한 redirection

류건 2024. 8. 14. 14:43
반응형

문제사항

 

spring google 소셜 로그인 구현 중 SuccessHandler에 리디렉션 url을 설정하여 로그인이 잘 되는지 테스트하고 있는 도중에, 갑자기 무한 리다이렉트 되는 현상을 발견했다...!

ㅠㅠ

OAuth2SuccessHandler

핸들러 코드를 살펴보자...

@Component
@Slf4j
public class OAuth2SuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException {

        log.info("success handler 실행");

        if (authentication.getPrincipal() instanceof OAuth2User) {
            CustomOauth2UserDetails principal = (CustomOauth2UserDetails) authentication.getPrincipal();

            Member member = principal.getMember();
            log.info("member : {} {} ", member.getId(), member.getEmail()); // 수정된 부분

            if (member.getEmail().equals("ryu7844@gmail.com")) {
                String redirectionUri = UriComponentsBuilder.fromUriString("http://localhost:8080/hello")
                        .queryParam("email", member.getEmail())
                        .build()
                        .toUriString();
                response.sendRedirect(redirectionUri);

            } else {
                String redirectionUri = UriComponentsBuilder.fromUriString("http://localhost:8080/hello")
                        .queryParam("token", "hello")
                        .build()
                        .toUriString();
                response.sendRedirect(redirectionUri);
            }
        } else {
            // OAuth2User가 아닌 경우
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
    }
}

 

위 방식으로 백엔드 url의 /hello 엔드포인트로 요청을 보냈을 때 무한 리디렉션이 일어나게 되었다...

 

해결

구글링을 계속해도 불구하고 마땅한 답변이 나오지 않아 현재 현업에서 종사하시는 형님께 여쭤보았다.

 

결론적으로 redirection은 해당 url로 GET 요청을 보내는 것.

 

/hello 라는 엔드포인트가 구현이 되어있는지 물어보셨다. (여기서 살짝 쎄함을 느끼는데...)

 

해당 엔드포인트가 구현이 안되어있기 때문에 계속 success handler가 작동을 하게 된다는 것!

 

그래서 localhost:3000 이라는 빈 포트로 리디렉션해보니 정상적으로 작동하였다!

 

String redirectionUri = UriComponentsBuilder.fromUriString("http://localhost:3000/hello")
                        .queryParam("token", "hello")
                        .build()
                        .toUriString();
response.sendRedirect(redirectionUri);
반응형