簡體   English   中英

用於RememberMeAuthenticationFilter的Spring Security authenticationSuccessHandler

[英]Spring Security authenticationSuccessHandler for RememberMeAuthenticationFilter

我想為我的登錄過濾器實現一個自定義AuthenticationSuccessHandler ,它是org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter

這是我的spring安全配置

<?xml version="1.0" encoding="UTF-8"?>
<beans 
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <security:http entry-point-ref="restAuthenticationEntryPoint" disable-url-rewriting = "true" auto-config="true" use-expressions="true">
        <security:intercept-url pattern="/api/*" access="hasRole('AUTHENTICATED_USER')"/>
        <security:remember-me key="spring_login_detail" services-ref="rememberMeServices"/>
        <security:form-login login-processing-url="/login"/>

        <security:logout
            invalidate-session="true"
            delete-cookies="JSESSIONID,SPRING_SECURITY_REMEMBER_ME_COOKIE"
            logout-url="/logout" 
        />
    </security:http>

    <security:global-method-security secured-annotations="enabled"  pre-post-annotations="enabled"/>

    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider ref="rememberMeAuthenticationProvider"/>
        <security:authentication-provider user-service-ref="customUserDetailsService">
            <security:password-encoder ref="passwordEncoder"/>
        </security:authentication-provider>
    </security:authentication-manager>

    <bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/>

    <bean id="mySuccessHandler" class="com.projectname.security.CustomSavedRequestAwareAuthenticationSuccessHandler"/>

    <bean id="customUserDetailsService" class="com.projectname.security.CustomUserDetailsService"/>

    <bean id="rememberMeServices" class="org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
        <property name="key" value="jsfspring-sec" />
        <property name="userDetailsService" ref="customUserDetailsService" />
        <property name="alwaysRemember" value="false" />
        <property name="tokenValiditySeconds" value="1209600" />
        <property name="parameter" value="_spring_security_remember_me_input"/>
    </bean>

    <bean id="rememberMeAuthenticationProvider" class="org.springframework.security.authentication.RememberMeAuthenticationProvider">
        <property name="key" value="spring_login_detail"/>
    </bean>

    <bean id="rememberMeFilter" class="org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter">
        <property name="rememberMeServices" ref="rememberMeServices"/>
        <property name="authenticationManager" ref="authenticationManager" />
        <property name="authenticationSuccessHandler" ref="mySuccessHandler"/>
    </bean> 

</beans>

這是我的自定義AuthenticationSuccessHandler實現

import java.io.IOException;
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.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;

public class CustomSavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RequestCache requestCache = new HttpSessionRequestCache();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws ServletException, IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if (savedRequest == null) {
            clearAuthenticationAttributes(request);
            return;
        }

        String targetUrlParam = getTargetUrlParameter();
        if (isAlwaysUseDefaultTargetUrl()
                || (targetUrlParam != null
                && StringUtils.hasText(request.getParameter(targetUrlParam)))) {
            requestCache.removeRequest(request, response);
            clearAuthenticationAttributes(request);
            return;
        }

        clearAuthenticationAttributes(request);
    }

    public void setRequestCache(RequestCache requestCache) {
        this.requestCache = requestCache;
    }
}

問題是在成功驗證之后根本沒有調用onAuthenticationSuccess 我在StackOverflow上讀到了一個答案,說我需要實現onAuthenticationSuccess而不是SimpleUrlAuthenticationSuccessHandler 我試過這樣做,仍然沒有奏效。 其他一切都很好,唯一的問題是每次我登錄時,春天只是將我重定向到'/' 這不是我想要的,我希望它只是返回'200 OK'

假設我已經正確理解,無論身份驗證如何發生,您都希望在身份驗證成功時中斷過濾器鏈並發送HTTP響應代碼 ; 即它可以是登錄表單或記住我的身份驗證。

因此,首先,將以下邏輯添加到CustomSavedRequestAwareAuthenticationSuccessHandler

// place where applicable
if (authentication != null) {
  response.setStatus(HttpServletResponse.SC_OK);
}

其次,定義一個新的過濾器,例如:

class HttpResponseAuthenticationFilter extends RememberMeAuthenticationFilter {

  protected  void   onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) {
    super.onSuccessfulAuthentication(request, response, authResult);
    if (authResult != null) {
      response.setStatus(HttpServletResponse.SC_OK);
    }
  }

} 

第三,在security:http定義客戶文件管理器security:http部分為:

<custom-filter position="LAST" ref="myHttpResponseAuthFilter" />

第四,為您的form-login添加成功處理程序的引用,如下所示:

<form-login ... authentication-success-handler-ref="mySuccessHandler" ... />

因為表單身份驗證中缺少此功能。

此外,基於Spring Security的過濾器上的位置的文檔,建議您不要使用auto-config與自定義過濾器。

觀察:

  1. 您看到此行為的原因是,當您看到登錄表單時,它不是關於記住我的服務。 表單處理決定了最終目標URL。
  2. 在第一次之后,它是remember-me過濾器進行身份驗證並再次需要發送HTTP響應代碼。

我還建議閱讀這個答案,因為它更深入地了解了Spring Security中form-login,http-basic auth和remember-me服務之間的區別。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM