Spring Security 4并发会话控制无法正常工作

时间:2015-11-08 08:22:14

标签: java spring spring-mvc spring-security

我正在尝试使用Spring安全性4在我的Spring应用程序中启用并发会话控制。下面是代码和配置。但这不起作用。它允许多个会话使用相同的登录。

你能不能让我知道缺少什么?

安全配置

@Configuration
@ComponentScan(basePackages = { "com.idearealty.product.shopchat" })
@EnableWebSecurity(debug=true)
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true,order=Ordered.HIGHEST_PRECEDENCE)
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private AuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Autowired
    private HttpAuthenticationEntryPoint authenticationEntryPoint;


    @Autowired
    private AuthFailureHandler authFailureHandler;
    @Autowired
    private HttpLogoutSuccessHandler logoutSuccessHandler;

    public SecSecurityConfig() {
        super();
    }


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.eraseCredentials(true).authenticationProvider(authProvider());
    }

    @Override
    public void configure(final WebSecurity web) throws Exception {
        DefaultWebSecurityExpressionHandler d = new DefaultWebSecurityExpressionHandler();
        //d.setPermissionEvaluator(permissionEvaluator);
        web.debug(true)./*expressionHandler(d).*/ignoring().antMatchers("/favicon.ico","/resources/**");
    }

    protected SessionAuthenticationStrategy getConcurrentSessionControlStrategy()
    {
        ConcurrentSessionControlAuthenticationStrategy concurrenSessionControlStrategy= new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry());
        concurrenSessionControlStrategy.setMaximumSessions(1);
        concurrenSessionControlStrategy.setExceptionIfMaximumExceeded(false);

        SessionFixationProtectionStrategy sessionFixationProtectionStrategy = new SessionFixationProtectionStrategy();
        sessionFixationProtectionStrategy.setMigrateSessionAttributes(false);

        RegisterSessionAuthenticationStrategy registerSessionAuthenticationStrategy = new RegisterSessionAuthenticationStrategy(sessionRegistry());

        List<SessionAuthenticationStrategy> strategies = new LinkedList<>();
        strategies.add(concurrenSessionControlStrategy);
        strategies.add(sessionFixationProtectionStrategy);
        strategies.add(registerSessionAuthenticationStrategy);

        CompositeSessionAuthenticationStrategy compositeSessionAuthenticationStrategy = new CompositeSessionAuthenticationStrategy(strategies);

        return compositeSessionAuthenticationStrategy;
    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception {

        // @formatter:off
        http
        .csrf().disable()
        //.and()
        .authorizeRequests()
        .antMatchers("/login*", "/logout*", "/signin/**", "/signup/**","/image/**","/useroperation/getLocality.json","/useroperation/getAllCities.json",
                "/user/registration*", "/regitrationConfirm*", "/user/regitrationConfirm*", "/expiredAccount*", "/registration*","/otpverification*","/user/otpverification*",
                "/badUser*", "/user/resendRegistrationToken*" ,"/forgetPassword*", "/user/resetPassword*","/user/regenerateOtp*","/products/getAllProductsByCategory**",
                "/user/changePassword*", "/emailError*", "/resources/**","/successRegister*","/anonymqestionanswer*").permitAll()
                .antMatchers("/invalidSession*").anonymous()
                .antMatchers("/admin","/admin/**").fullyAuthenticated()
                .antMatchers("/admin","/admin/**").fullyAuthenticated()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.html")
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/homepage.html")
                .failureUrl("/login.html?error=true")
                .successHandler(myAuthenticationSuccessHandler)
                //.successHandler(authSuccessHandler)
                .failureHandler(authFailureHandler)
                .usernameParameter("username")
                .passwordParameter("password")
                .permitAll()
                .and()
                .logout()
                .invalidateHttpSession(true)
                .logoutUrl("/logout")
                .logoutSuccessUrl("/logout.html?logSucc=true")
                .deleteCookies("JSESSIONID")
                .permitAll()
            .and()
                .sessionManagement()
                      .sessionAuthenticationStrategy(getConcurrentSessionControlStrategy())//.maximumSessions(1).maxSessionsPreventsLogin(true)
                ;

        // @formatter:on
    }


    @Bean
    public SessionRegistry sessionRegistry() {
        SessionRegistry sessionRegistry = new SessionRegistryImpl();
        return sessionRegistry;
    }

    // beans

    @Bean
    public DaoAuthenticationProvider authProvider() {
        final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService);
        //authProvider.setPasswordEncoder(encoder());
        return authProvider;
    }
    /*
    @Bean
    public PasswordEncoder encoder() {
        return new BCryptPasswordEncoder(11);
    }
     */
}

的web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
         http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
      <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>localizationFilter</filter-name>
        <filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>localizationFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

0 个答案:

没有答案