Spring Security记住我使用mongodb和Spring Data

时间:2015-01-14 13:19:47

标签: java mongodb spring-security

我尝试使用Spring Security来保护我的应用。登录代码如下

//get UserDetails ....
UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
HttpSession session = request.getSession(true);
session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());

现在我想让Spring Security记住用户登录,但我想用我的代码来做。 请告诉我如何。

谢谢!

我尝试使用一种简单的方法。我使用TokenBasedRememberMeServices来记住我。

<bean id="rememberMeServices" class="org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
        <property name="userDetailsService" ref="myUserDetailService"></property>
        <property name="key" value="myRememberMeKey"></property>
        <property name="alwaysRemember" value="true"></property>
</bean>

而且

<http auto-config="true" use-expressions="true">
        <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
        <form-login login-processing-url="/j_spring_security_check"
                    login-page="/login.jsp"
                    authentication-failure-url="/login.jsp"/>
        <remember-me services-ref="rememberMeServices" />
</http>

userDetailService是

public class MyUserDetailService implements UserDetailsService {
    @Resource
    private UserDao userDaoImp; 
    @Override
    public UserDetails loadUserByUsername(String userName)
            throws UsernameNotFoundException {
        User user = new User();
        user.setName(userName);
        List<User>ulist = userDaoImp.find(user);
        if(ulist.size() == 1){
            return (UserDetails) (ulist.toArray())[0];
        }
        return null;
    }
}

当我从登录页面登录时,有一个cookie:SPRING_SECURITY_REMEMBER_ME_COOKIE 但是当我关闭webbrowser并再次打开它时,它仍然会变成登录页面。并设置了SPRING_SECURITY_REMEMBER_ME_COOKIE&#34;&#34;。 我做错了什么?

0 个答案:

没有答案