Java/Spring Framework

[Spring Framework] 스프링 시큐리티에서 로그인 성공 후 로그인 전 요청했던 URL로 리다이렉트 하기

크리스피코드 2023. 3. 24. 21:46

0. AuthenticationSuccessHandler

스프링 시큐리티에서는 authentication-success-hander-ref 를 통해 로그인에 성공했을 경우 작업을 수행할 클래스를 설정할 수 있다. 이 경우 로그인 했을 때 필요한 작업을 수행할 수 있지만 onAuthenticationSuccess()의 파라미터로 받는 HttpServletRequest 또는 HttpServletResponse를 사용해 다음으로 진행할 경로를 지정해주어야 한다.

 

 

1.  SavedRequestAwareAuthenticationSuccessHandler

AuthenticationSuccessHandler를 사용하지 않았을 경우, 스프링 시큐리티에서는 기본적으로 SavedRequestAwareAuthenticationSuccessHandler 라는 클래스를 사용해 사용자가 로그인 하기 전 요청했던 경로로 리다이렉트해준다.

 

사용자 임의의 AuthenticationSuccessHandler를 사용할 때에도 위 클래스의 onAuthenticationSuccess() 메서드를 통해 로그인 후 작업을 수행하고 요청했던 경로로 리다이렉트 해줄 수 있다.

 

 

<bean id="savedRequestAwareAuthenticationSuccessHandler"
      class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler" />

<bean id="customAuthenticationSuccessHandler"
      class="com.web.spring.security.CustomAuthenticationSuccessHandler" />

    ...

<security:form-login login-page="/login"
                     login-processing-url="/login"
                     username-parameter="memId" password-parameter="memPw"
                     authentication-success-handler-ref="customAuthenticationSuccessHandler" />
                     
    ...

 

 

package com.web.ddentist.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

public class RememberIdHandler implements AuthenticationSuccessHandler {
	
    @Autowired
    private SavedRequestAwareAuthenticationSuccessHandler savedRequestAwareAuthenticationSuccessHandler;
    
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
		
        System.out.println("-----------------------");
        System.out.println("작업 수행");
        System.out.println("-----------------------");
        
        savedRequestAwareAuthenticationSuccessHandler.onAuthenticationSuccess(request, response, authentication);
    }

}