복붙노트

[SPRING] 스프링 보안 3.1에서 역할에 따라 목표 URL 결정

SPRING

스프링 보안 3.1에서 역할에 따라 목표 URL 결정

스프링 보안 3.0에서는 다양한 역할을 기반으로 url을 반환하는 decideTargetUrl () 메서드를 사용하는 AuthenticationProcessingFilter 클래스를 사용하고 있습니다.

이제 우리는 스프링 보안 3.1.0.RC3으로 이동하고 있습니다. 이제 AuthenticationProcessingFilter 클래스가 새 버전에서 제거되어 어떻게 다른 역할을 기반으로 URL을 결정해야합니까? 누구든지 다른 역할에 대해 다른 페이지로 리디렉션하는 사용자 지정 필터를 구현할 수 있도록 몇 가지 코드로 단계를 밟아 주시겠습니까.

해결법

  1. ==============================

    1.역할을 기준으로 대상 URL을 결정하는 가장 좋은 방법은 아래와 같이 Spring Security 구성에서 대상 URL을 지정하는 것입니다. 이것은 Spring 3.0 또는 3.1에서 작동합니다.

    역할을 기준으로 대상 URL을 결정하는 가장 좋은 방법은 아래와 같이 Spring Security 구성에서 대상 URL을 지정하는 것입니다. 이것은 Spring 3.0 또는 3.1에서 작동합니다.

    <http>
        ... 
        <form-login login-page="/login" default-target-url="/default"/>
    </http>
    

    그런 다음 default-target-url을 처리하는 컨트롤러를 만듭니다. 컨트롤러는 롤을 기준으로 리디렉션 또는 전달해야합니다. 아래는 Spring MVC를 사용하는 예제입니다. 그러나 모든 유형의 컨트롤러 (Struts, Servlet 등)가 작동합니다.

    @Controller
    public class DefaultController {
        @RequestMapping("/default")
        public String defaultAfterLogin(HttpServletRequest request) {
            if (request.isUserInRole("ROLE_ADMIN")) {
                return "redirect:/users/sessions";
            }
            return "redirect:/messages/inbox";
        }
    }
    

    이 접근 방식의 장점은 특정 보안 구현과 결합되지 않으며 특정 MVC 구현과 결합되지 않으며 스프링 보안 네임 스페이스 구성으로 쉽게 작동한다는 점입니다. 전체 예제는 올해 SpringOne에서 발표 한 SecureMail 프로젝트에서 찾을 수 있습니다.

    대안으로 사용자 정의 AuthenticationSuccessHandler를 생성 할 수 있습니다. 구현시 기본 AuthenticationSuccessHandler 인 SavedRequestAwareAuthenticationSuccessHandler를 확장 할 수 있습니다. 다음과 같이 네임 스페이스를 사용하여 연결할 수 있습니다.

    <sec:http>
        <sec:form-login authentication-success-handler-ref="authSuccessHandler"/>
    </sec:http>
    <bean:bean class="example.MyCustomAuthenticationSuccessHandler"/>
    

    스프링 보안 API에 묶여 있으므로이 작업을 권장하지 않으며 가능한 경우이를 피하는 것이 좋습니다.

  2. ==============================

    2.사용자 지정 인증 성공 처리기를 사용하여 성공적인 인증 후에 사용자 역할을 기반으로 리디렉션을 지정합니다.

    사용자 지정 인증 성공 처리기를 사용하여 성공적인 인증 후에 사용자 역할을 기반으로 리디렉션을 지정합니다.

    다음과 같이 사용자 지정 인증 성공 처리기를 만들어야합니다.

    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.web.DefaultRedirectStrategy;
    import org.springframework.security.web.RedirectStrategy;
    import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.Collection;
    
    public class CustomeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    
        private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request,
                                            HttpServletResponse response, Authentication authentication) throws IOException {
            handle(request, response, authentication);
        }
    
        protected void handle(HttpServletRequest request,
                              HttpServletResponse response, Authentication authentication)
                throws IOException {
            String targetUrl = determineTargetUrl(authentication);
            if (response.isCommitted()) {
                return;
            }
            redirectStrategy.sendRedirect(request, response, targetUrl);
        }
    
        protected String determineTargetUrl(Authentication authentication) {
            boolean isTeacher = false;
            boolean isAdmin = false;
            Collection<? extends GrantedAuthority> authorities
                    = authentication.getAuthorities();
    
            for (GrantedAuthority grantedAuthority : authorities) {
                if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
                    isTeacher = true;
                    break;
                } else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
                    isAdmin = true;
                    break;
                }
            }
    
            if (isTeacher) {
                return "/user/account";
            } else if (isAdmin) {
                return "/admin/account";
            } else {
                throw new IllegalStateException();
            }
        }
        public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
            this.redirectStrategy = redirectStrategy;
        }
    
        protected RedirectStrategy getRedirectStrategy() {
            return redirectStrategy;
        }
    }
    

    그런 다음 스프링 보안 xml 파일을 수정하고 bean을 정의한 다음 사용하십시오

       <bean id="customeAuthenticationSuccessHandler"
              class="com.test.CustomeAuthenticationSuccessHandler"/>
        <security:http auto-config="true" use-expressions="false">
            <security:form-login login-page="/sign-in" login-processing-url="/sign-in" username-parameter="username"
                                 password-parameter="password"
                                 authentication-success-handler-ref="customeAuthenticationSuccessHandler"
                                 always-use-default-target="true"
                                 authentication-failure-url="/sign-in?error=true"/>
    
            <security:logout logout-url="/logout" logout-success-url="/"/>
         ..
         ..
        </security:http>
    
  3. from https://stackoverflow.com/questions/8326587/determine-target-url-based-on-roles-in-spring-security-3-1 by cc-by-sa and MIT license