春天的安全记住 - 我没有工作

时间:2015-07-13 11:27:33

标签: spring remember-me

我尝试将Spring安全性应用于自定义用户详细信息服务和自定义身份验证提供程序。 此外,我正在尝试应用记忆功能。

然而,不知何故,在我配置自定义用户详细信息服务和自定义身份验证提供程序之后,请记住我停止工作。

当我从客户端浏览器检查cookie时,它有记住我的cookie。 但是,如果我重新部署(重新启动)服务器或重新启动客户端浏览器,它将重定向到登录页面。

我在这里附加配置文件和自定义文件。

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

       <!-- enable use-expressions -->
       <security:annotation-config/>
       <http auto-config="false" use-expressions="true">

              <headers>
                     <cache-control />
              </headers>


              <intercept-url pattern="/resources/**" access="permitAll()"/>
              <intercept-url pattern="/signin" access="permitAll()" />
              <intercept-url pattern="/403" access="permitAll()" />
              <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />

              <!-- redirect to 403 access denied <intercept-url pattern="/update**" access="hasRole('ROLE_ADMIN')
                  and isFullyAuthenticated()" /> -->

              <form-login login-page="/signin"
                          default-target-url="/"
                          authentication-failure-url="/signin?error"
                          username-parameter="username"
                          password-parameter="password"
                          login-processing-url="/auth/login_check"
                          authentication-success-handler-ref="loginSuccessHandler" />

              <logout logout-url="/logout" logout-success-url="/signin?logout" delete-cookies="JSESSIONID" />
              <!-- enable csrf protection -->
              <!--<csrf disabled="true"/>-->

              <!--<remember-me-->
                      <!--token-validity-seconds="1209600"-->
                      <!--remember-me-parameter="remember-me"-->
                      <!--data-source-ref="dataSource" user-service-ref="customUserDetailService"/>-->
               <remember-me services-ref="rememberMeServices" />
                <csrf disabled="true"/>
            <!--<custom-filter ref="statelessCSRFFilter" before="CSRF_FILTER"/>-->


       </http>

       <!-- Select users and user_roles from database -->
       <!--<authentication-manager>-->
              <!--<authentication-provider>-->
                     <!--<jdbc-user-service data-source-ref="dataSource"-->
                                        <!--users-by-username-query="select username,password, enabled from users where username=?"-->
                                        <!--authorities-by-username-query="select username, role from user_roles where username =?  "-->
                             <!--group-authorities-by-username-query="select  g.id, g.group_name, ga.authority from groups g, group_members gm, group_authorities ga where gm.username = ? and g.id = ga.group_id and g.id = gm.group_id"/>-->
              <!--</authentication-provider>-->
       <!--</authentication-manager>-->


        <beans:bean id="customUserDetailService" class="com.euroscope.app.service.security.CustomUserService"></beans:bean>

        <beans:bean id="customAuthenticationProvider" class="com.euroscope.app.handler.CustomAuthenticationProvider"></beans:bean>

        <beans:bean id="loginSuccessHandler" class="com.euroscope.app.handler.LoginSuccessHandler"></beans:bean>





    <!--<beans:bean id="statelessCSRFFilter" class="com.euroscope.app.filter.StatelessCSRFFilter" />-->

        <beans:bean id="rememberMeFilter" class= "org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter">
            <beans:constructor-arg ref="authenticationManager"/>
            <beans:constructor-arg ref="rememberMeServices"/>
        </beans:bean>

        <beans:bean id="rememberMeServices" class= "org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
            <beans:constructor-arg value="euroscope"/>
            <beans:constructor-arg ref="customUserDetailService"/>
            <beans:constructor-arg ref="tokenRepository" />
            <beans:property name="alwaysRemember" value="true" />
        </beans:bean>

        <beans:bean id="rememberMeAuthenticationProvider" class= "org.springframework.security.authentication.RememberMeAuthenticationProvider">
            <beans:constructor-arg value="euroscope"/>
        </beans:bean>

        <beans:bean id="tokenRepository" class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl">
            <beans:property name="dataSource" ref="dataSource"/>
        </beans:bean>


        <authentication-manager alias="authenticationManager">

            <authentication-provider ref="rememberMeAuthenticationProvider" />
            <authentication-provider ref="customAuthenticationProvider" />
            <authentication-provider user-service-ref="customUserDetailService" />
        </authentication-manager>

</beans:beans>

登录成功处理程序

@Component
@Slf4j
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException, ServletException
    {

        HttpSession session = request.getSession();
        Employee employee = (Employee)auth.getPrincipal();
        log.debug("Employee : "+employee);
        session.setAttribute("employee",employee);
        response.sendRedirect(request.getContextPath() + "/");
    }
}
package com.euroscope.app.handler;

import com.euroscope.app.domain.security.Employee;
import com.euroscope.app.service.security.CustomUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * Created by ksyeng on 7/9/15.
 */
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationProvider.class);

    @Autowired
    CustomUserService customUserService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {


        String username = authentication.getName();
        String password = (String) authentication.getCredentials();

        Employee employee;
        Collection<? extends GrantedAuthority> authorities;

        try {
            logger.debug("Custom Authentication : "+authentication);
            employee = (Employee)customUserService.loadUserByUsername(username);
//            employee = customUserService.loadUserByUsername(username);

//            String hashedPassword = passwordEncoder.encodePassword(password, saltSource.getSalt(user));

//            log.info("username : " + username + " / password : " + password + " / hash password : " + hashedPassword);
            logger.debug("Username : " + employee.getUsername() + " / Password : " + employee.getPassword());

//            if (!hashedPassword.equals(user.getPassword())) throw new BadCredentialsException("비밀번호가 일치하지 않습니다.");

            authorities = employee.getAuthorities();
            return new UsernamePasswordAuthenticationToken(employee, password, authorities);
        } catch(UsernameNotFoundException e) {
            e.printStackTrace();
            logger.debug(e.toString());
            throw new UsernameNotFoundException(e.getMessage());
        } catch(BadCredentialsException e) {
            e.printStackTrace();
            logger.debug(e.toString());
            throw new BadCredentialsException(e.getMessage());
        } catch(Exception e) {
            e.printStackTrace();
            logger.debug(e.toString());
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}

自定义用户服务

package com.euroscope.app.service.security;

import com.euroscope.app.domain.security.Employee;
import com.euroscope.app.domain.security.Role;
import com.euroscope.app.mapper.security.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * Created by ksyeng on 7/9/15.
 */
@Slf4j
@Service
public class CustomUserService implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Employee employee = userMapper.getUser(username);
        ArrayList<Role> authList = userMapper.getRoles(username);
        log.debug("Auth Roles : "+authList.toString());
        employee.setAuthorities(authList);

        if(employee == null){
            throw new UsernameNotFoundException("Can't Find Any Matching User");
        }

        log.debug(employee.toString());

        return employee;
    }
}

1 个答案:

答案 0 :(得分:0)

无论您使用哪种身份验证过滤器(即AbstractAuthenticationProcessingFilter的子类),都需要了解RememberMeServices,例如:

<beans:bean .. class="x.x..YourCustomAuthenticationFilter">
  <beans:property name="rememberMeServices" ref="rememberMeServices"/>
  <beans:property name="authenticationManager" ref="authenticationManager"/>
</beans:bean>

RememberMeAuthenticationFilter应在YourCustomAuthenticationFilter

之后注册