복붙노트

[SPRING] 내가 얻은 오류에 따라 SPRING_SECURITY_LAST_EXCEPTION.message를 사용자 정의하는 방법

SPRING

내가 얻은 오류에 따라 SPRING_SECURITY_LAST_EXCEPTION.message를 사용자 정의하는 방법

Spring Security로 로그인 시스템을 만들었습니다. 이것은 나의 spring-security.xml이다.

... 
<session-management invalid-session-url="/login">
       <concurrency-control max-sessions="1" expired-url="/login" error-if-maximum-exceeded="true"/>
</session-management>

<form-login 
        login-page="/login"                         
        default-target-url="/index" 
        always-use-default-target="true"
        authentication-failure-url="/login?error=true"          
        username-parameter="j_username"         
        password-parameter="j_password" />

<logout
        logout-success-url="/login"          
        delete-cookies="JSESSIONID" 
        invalidate-session="true" />     
    ...

이후 나는이 줄을 authentication-failure-url = "/ login? error = true" 오류가 'true'인 경우 오류가 발생합니다. '나쁜 자격증 명'또는 '최대 세션 수 초과'일 수 있습니다. 그러나 실제로 어떤 오류가 발생했는지 알고 싶습니다.

자바 클래스 (@controller) 안에 스프링이 어떤 오류를 내고 있는지를 알기위한 방법이 있습니까? 이러한 오류 메시지를 사용자 정의하려면 어떻게해야합니까?

해결법

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

    1.나는이 해결책을 발견했다.

    나는이 해결책을 발견했다.

    SimpleUrlAuthenticationFailureHandler를 확장하면 사용자를 다른 페이지로 보내고 원하는 메시지를 인쇄 할 수 있습니다.

    나의 주된 목표는 SPRING_SECURITY_LAST_EXCEPTION.message를 "오버 라이드 (override)"하는 것이 아니라 스프링 보안이 제공하는 다양한 종류의 오류에 따라 오류 메시지를 사용자 정의하는 것이 었습니다.

    을 포함한다.

      <listener>
        <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
      </listener>
    

    security-config.xml (일부 코드)

    세션 관리

       <session-management invalid-session-url="/login" session-authentication-error-url="/login" >
                       <concurrency-control max-sessions="1" expired-url="/login" error-if-maximum-exceeded="true"/>
                </session-management> 
    

    자신의 AuthenticationFailureHandler (custom FailureHandler)를 호출하는 form-login

      <form-login 
                        login-page="/login"         
                        default-target-url="/index" 
                        always-use-default-target="true"                  
                        authentication-failure-handler-ref="customFailureHandler"   
                        username-parameter="j_username"         
                        password-parameter="j_password" />
    

    자신의 AuthenticationFailureHandler의 bean

     <beans:bean id="customFailureHandler" class="com.springgestioneerrori.controller.CustomAuthenticationFailureHandler"/>
    

    이것은 SimpleUrlAuthenticationFailureHandler를 구현하는 클래스입니다.

    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.security.authentication.BadCredentialsException;
    import org.springframework.security.authentication.DisabledException;
    import org.springframework.security.core.AuthenticationException;
    import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
    import org.springframework.security.web.authentication.session.SessionAuthenticationException;
    
    public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { 
    
        @Override
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
    
         if(exception.getClass().isAssignableFrom(BadCredentialsException.class)) {
                setDefaultFailureUrl("/url1");
          }
          else if (exception.getClass().isAssignableFrom(DisabledException.class)) {         
              setDefaultFailureUrl("/url2");
          }
          else if (exception.getClass().isAssignableFrom(SessionAuthenticationException.class)) {       
              setDefaultFailureUrl("/url3");    
          }
    
          super.onAuthenticationFailure(request, response, exception);  
    
        }
    
    }
    

    희망이 사람을 도울 수 있습니다.

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

    2.authentication-failure-url 대신에 authentication-failure-handler-ref를 사용하고 다른 URL 유형 (또는 다른 URL에 다른 매개 변수)을 작성하고 다른 유형의 예외에 맵핑해야하는 실패 핸들러 bean을 참조해야합니다.

    authentication-failure-url 대신에 authentication-failure-handler-ref를 사용하고 다른 URL 유형 (또는 다른 URL에 다른 매개 변수)을 작성하고 다른 유형의 예외에 맵핑해야하는 실패 핸들러 bean을 참조해야합니다.

     <form-login 
        login-page="/login"                         
        default-target-url="/index" 
        always-use-default-target="true"
        authentication-failure-handler-ref="customFailureHandler"          
        username-parameter="j_username"         
        password-parameter="j_password" />
    
    
    <beans:bean id="customFailureHandler"
        class="org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler">
        <beans:property name="exceptionMappings">
            <beans:props>
                <beans:prop
                    key="org.springframework.security.authentication.BadCredentialsException">/url1</beans:prop>
                <beans:prop
                    key="org.springframework.security.authentication.AuthenticationServiceException">/url2</beans:prop>
                <beans:prop key="org.springframework.secuirty.authentication.DisabledException">/url3</beans:prop>
            </beans:props>
        </beans:property>
        <beans:property name="defaultFailureUrl" value="/url4" />
    </beans:bean>
    

    문서에 언급 된 다른 예외가 많이 있습니다. 문서를 참조하십시오.

    편집하다:

    동일한 예외가 있습니다. SessionAuthenticationException은 일반적으로 동일한 사용자가 동시에 허용 할 수있는 세션 수를 초과했기 때문에 throw됩니다. 그러나 이는 컨테이너 수준에서만 발생하며 여러 컨테이너가있는 경우 작동하지 않습니다.

    <security:session-management session-authentication-strategy-ref="sas"/>
    
    <bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl" />
    <bean id="sas" class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy" >
        <constructor-arg name="sessionRegistry" ref="sessionRegistry" />
        <property name="maximumSessions" value="2" />
     </bean>
    
  3. ==============================

    3.이것은 오래된 질문이지만 올바른 것으로 표시된 답변에는 불쾌한 미묘한 버그가 포함되어 있으므로 올바른 해결책은 @mdp의 대답에 제안 된 CustomAuthenticationFailureHandler 대신 내장 된 ExceptionMappingAuthenticationFailureHandler를 사용하는 것입니다.

    이것은 오래된 질문이지만 올바른 것으로 표시된 답변에는 불쾌한 미묘한 버그가 포함되어 있으므로 올바른 해결책은 @mdp의 대답에 제안 된 CustomAuthenticationFailureHandler 대신 내장 된 ExceptionMappingAuthenticationFailureHandler를 사용하는 것입니다.

  4. from https://stackoverflow.com/questions/26484440/how-to-customize-spring-security-last-exception-message-according-to-the-error-i by cc-by-sa and MIT license