본문 바로가기
개발/Spring

[Spring Security] Login 이 성공했을 때 후처리를 어떻게 할 수 있을까?

by 상용최 2021. 4. 3.
반응형

Spring Security를 쓰면 Login이 손쉽게 구현할 수 있다.

하지만 우리는 Login이 성공했을 때 추가로 작업을 해줘야 하는 상황들이 많이 있다.
대표적인 예가 토큰을 발급해서 내려준다든지 쿠키나 헤더에 어떠한 값들을 세팅을 해줘야 할 때가 종종 있다.

어떻게 할 수 있는지 알아보도록 하겠다.

 

방법은 매우 간단하다.

Spring Security에 존재하는 AuthenticationSuccessHandler 인터페이스를 구현하기만 하면 된다.

 

AuthenticationSuccessHandler 은 총 2개의 메소드로 이루어져 있고 그 중 하나는 default 메소드이다.

이 인터페이스를 구현한 Handler 클래스를 하나 생성한다.

public class LoginAuthHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setStatus(HttpStatus.OK.value());
    }
}

 

그 후 Security Config를 설정해주는 곳에서 Login SuccessHandler 를 사용한다고 명시해준다.

반응형

댓글