在Spring安全性中使用基于令牌的rememberMeService和自定义AuthenticationHandler

时间:2013-11-01 09:31:01

标签: spring cookies spring-security remember-me

我有以下配置:

<security:http auto-config="false" entry-point-ref="restAuthenticationEntryPoint" use-expressions="true">
        <security:remember-me services-alias="rememberMyCompamy" key="MY-KEY" user-service-ref="myUserDetailsService"/>
        <security:custom-filter ref="loginFilter" position="FORM_LOGIN_FILTER"/>
        <!-- Adds a logout filter to Spring Security filter chain -->
        <security:logout logout-url="/logout" delete-cookies="true" invalidate-session="true" success-handler-ref="restLogoutSuccessHandler"/>
    </security:http>
    <!-- Configures the authentication entry point that returns HTTP status code 401 -->
    <bean id="restAuthenticationEntryPoint" class="uk.co.axiomtechsolutions.ipf.security.authentication.RestAuthenticationEntryPoint"/>

    <!-- Configures a custom login filter bean -->
    <bean id="loginFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="authenticationFailureHandler" ref="restAuthenticationFailureHandler"/>
        <property name="authenticationSuccessHandler" ref="restAuthenticationSuccessHandler"/>
        <property name="rememberMeServices" ref="rememberMyCompany"/> <!--doesn't do anything?-->
        <property name="filterProcessesUrl" value="/login"/>
        <property name="usernameParameter" value="username"/>
        <property name="passwordParameter" value="password"/>
        <property name="allowSessionCreation" value="true"/>
        <property name="postOnly" value="true"/>
    </bean>

在我的AuthenticationSuccesHandler中使用此代码,该代码有效。我尝试了一些组合,这是唯一一个获得创建cookie的方法,取自优秀的教程here。然而,程序性地调用rememberMeservice但感觉正确

@Resource(name = "rememberMyCompany")
private RememberMeServices rememberMyCompany;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                    Authentication authentication) throws ServletException, IOException {

    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {
        @Override public String getParameter(String name) {
            return "true";
        }
    };
    rememberMyCompnay.loginSuccess(wrapper, response, authentication);
    clearAuthenticationAttributes(request);
}

创建基于令牌的rememberMeService以及服务别名,但我无法设置登录过滤器以使用它,除非我执行上述操作,这不会感到非常有弹性。

1 个答案:

答案 0 :(得分:1)

UsernamePasswordAuthenticatonFilter将为您调用RememberMeServicesbefore your authentication success handler executes。它是否做任何事情取决于the request contains the "remember me" parameter

所以我猜你在请求中没有那个参数。从你的问题中确切地说你正在努力实现的目标并不清楚 - 你是否意识到这一点,并且想要为所有请求启用记住我。要始终为经过身份验证的请求设置Cookie,您可以在alwaysRemember上设置RememberMeServices标记。但是,这不是通过命名空间公开的,所以你必须获得对bean的引用并以这种方式执行(例如通过后处理器),或者手动声明bean。