본문 바로가기

Spring/Spring Security

[Spring Security] 3. AuthenticationSuccessHandler 구현

728x90
반응형

AuthenticationSuccessHandler란?

로그인 성공 후 특정 동작을 제어하기 위해 구현하는 인터페이스

(ex. admin 계정으로 로그인 시 어떤 경로로 로그인 페이지로 들어오든 무조건 '/sample/admin'으로 이동하도록 하고 싶을 때, 혹은 별도의 쿠키 등을 생성해서 처리하고 싶을 때)

 

설정

src/main/java/__.__.security(패키지명)/CustomLoginSuccessHandler

package com.goodluxe.security;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import lombok.extern.log4j.Log4j;

@Log4j
public class CustomLoginSuccessHandler implements AuthenticationSuccessHandler {

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication auth) throws IOException, ServletException {
		log.warn("Login Success");
		
		List<String> roleNames = new ArrayList<>();
		
		auth.getAuthorities().forEach(authority -> {
			roleNames.add(authority.getAuthority());
		});

		log.warn("ROLE NAMES: " + roleNames);
		
		if(roleNames.contains("ROLE_ADMIN")) {
			response.sendRedirect("/sample/admin");
			return;
		}
		
		if(roleNames.contains("ROLE_MEMBER")) {
			response.sendRedirect("/sample/member");
			return;
		}
		
		response.sendRedirect("/");
	}
}

로그인 한 사용자에 부여된 권한 Authentication 객체 이용하여 사용자가 가진 모든 권한을 문자열로 체크한 후, 'ROLE_ADMIN' 권한을 가졌다면 로그인 완료 시 '/sample/admin'으로, 'ROLE_MEMBER' 권한을 가졌다면 로그인 완료 시 'sample/member'로 이동하는 방식이다.

 

security-context.xml

- customLoginSuccess <bean> 추가

- <security:form-login>에 authentication-success-handler-ref 추가

<bean id="customLoginSuccess" class="com.goodluxe.security.CustomLoginSuccessHandler"></bean>

<security:http>
	<security:form-login login-page="/customLogin" authentication-success-handler-ref="customLoginSuccess" />
</security:http>

 

 

728x90
반응형