【问题标题】:Spring Security Concurrent Session ControlSpring Security 并发会话控制
【发布时间】:2020-03-27 14:45:50
【问题描述】:

我试图从任何地方一次将用户会话限制为一个。但它不起作用。当我尝试在两个导航器上使用同一用户访问应用程序时,我可以访问。 我注意到,当用户连接到两台不同机器上的应用程序以开始打印两个不同的报告时,会出现一个打印件而不是另一个打印件。 感谢帮助。

我的安全配置类:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    /*@Autowired
    private DataSource dataSource;*/

    private AccessDeniedHandler accessDeniedHandler;
    private AuthenticationSuccessHandler authenticationSuccessHandler;
    private AuthenticationFailureHandler authenticationFailureHandler;
    private UserDetailsService userDetailsService;

    @Autowired
    public SecurityConfiguration( 
            @Qualifier("customAccessDeneiedHandler")AccessDeniedHandler accessDeniedHandler,
            @Qualifier("customSuccessHandler")AuthenticationSuccessHandler authenticationSuccessHandler,
            @Qualifier("customAuthenticationFailureHandler")AuthenticationFailureHandler authenticationFailureHandler,
            @Qualifier("customUserDetailsService")UserDetailsService userDetailsService) {
        this.accessDeniedHandler = accessDeniedHandler;
        this.authenticationSuccessHandler = authenticationSuccessHandler;
        this.authenticationFailureHandler = authenticationFailureHandler;
        this.userDetailsService = userDetailsService;
    }


    /* (non-Javadoc)
     * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder)
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // TODO Auto-generated method stub
        //super.configure(auth);

        auth.userDetailsService(userDetailsService)   //auth.userDetailsService(utilisateurDetailsService)
            .passwordEncoder(passwordEncoder());
    }

    //Authorization
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
                //.antMatchers("/").permitAll()
                .antMatchers("/ajouterassure", "/ajouterattributaire", "/ajouterbeneficiaire", "/ajouterpiecejustificative",
                             "/creerbordereauemission", "/creerbehorscoordination", "/creerbordereaupaie", "/ajouteravance", 
                             "/creerbeavanceannuelle")
                            .hasAnyRole("DGA", "DGAA", "DR", "DRA", "CC", "CCA", "CI", "AS", "GUICHET", "CE", "CAP", "ADMIN") //.hasRole("ADMIN")

                .antMatchers("/ajoutercentre", "/ajouteretablissementpaie", "/ajoutertypepj", "/ajoutertypedette",
                             "/ajoutersexe", "/ajoutersituationbeneficiaire", "/ajoutercategoriebeneficiaire", 
                             "/ajoutercategorieattributaire", "/ajouterrevalorisation").hasAnyRole("DGA", "ADMIN")  //hasAnyRole("CAP", "ADMIN")
                .antMatchers("/payerdecompte").hasAnyRole("CAISSIER", "ADMIN")
                .antMatchers("/ajouterutilisateur").hasAnyRole("CI", "ADMIN")
                .anyRequest().authenticated()
                .and()
                //.httpBasic()
            .formLogin()
                .loginPage("/login")
                //.loginProcessingUrl("/login")
                .usernameParameter("identifiant")
                .passwordParameter("mot_de_passe")
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler)
                //.defaultSuccessUrl("/")
                .permitAll()
                .and()
            .logout().permitAll()
                    .and()
                .sessionManagement()            //Session controle concurence access
                    .maximumSessions(1)
                    .expiredUrl("/login?expired")
                    .sessionRegistry(sessionRegistry);

        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);

        //Session controle concurence access
        //http.sessionManagement().maximumSessions(1);
    }

    /* (non-Javadoc)
     * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.WebSecurity)
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**", "/resources/templates/errors/**", "/static/**", "/css/**", "/images/**", "/var/signatures/**");
        //web.ignoring().antMatchers("/static/**");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }



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

    @Autowired
    @Lazy
    private SessionRegistry sessionRegistry;
}

【问题讨论】:

  • 你试过.maximumSessions(1).maxSessionsPreventsLogin(true)吗?
  • 我试过 .maximumSessions(1).maxSessionsPreventsLogin(true) 正如你所说,它工作正常。非常感谢。

标签: spring spring-boot spring-mvc spring-security


【解决方案1】:

[以防万一有人觉得它有用。]

始终在自定义 UserDetails 类中添加 hashcode 和 equals 方法以及 spring 安全配置类中的以下配置,以使并发会话正常工作。

protected void configure(HttpSecurity http) throws Exception 
{
    http.sessionManagement().maximumSessions(1);
}

@Bean
public HttpSessionEventPublisher httpSessionEventPublisher() 
{
    return new HttpSessionEventPublisher();
}

【讨论】:

    【解决方案2】:

    您只需在maximumSessions(1) 之后添加.maxSessionsPreventsLogin(true),它就会停止从其他地方登录 util session expires here。所以你的配置方法应该是这样的:-

    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
                //.antMatchers("/").permitAll()
                .antMatchers("/ajouterassure", "/ajouterattributaire", "/ajouterbeneficiaire", "/ajouterpiecejustificative",
                             "/creerbordereauemission", "/creerbehorscoordination", "/creerbordereaupaie", "/ajouteravance", 
                             "/creerbeavanceannuelle")
                            .hasAnyRole("DGA", "DGAA", "DR", "DRA", "CC", "CCA", "CI", "AS", "GUICHET", "CE", "CAP", "ADMIN") //.hasRole("ADMIN")
    
                .antMatchers("/ajoutercentre", "/ajouteretablissementpaie", "/ajoutertypepj", "/ajoutertypedette",
                             "/ajoutersexe", "/ajoutersituationbeneficiaire", "/ajoutercategoriebeneficiaire", 
                             "/ajoutercategorieattributaire", "/ajouterrevalorisation").hasAnyRole("DGA", "ADMIN")  //hasAnyRole("CAP", "ADMIN")
                .antMatchers("/payerdecompte").hasAnyRole("CAISSIER", "ADMIN")
                .antMatchers("/ajouterutilisateur").hasAnyRole("CI", "ADMIN")
                .anyRequest().authenticated()
                .and()
                //.httpBasic()
            .formLogin()
                .loginPage("/login")
                //.loginProcessingUrl("/login")
                .usernameParameter("identifiant")
                .passwordParameter("mot_de_passe")
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler)
                //.defaultSuccessUrl("/")
                .permitAll()
                .and()
            .logout().permitAll()
                    .and()
                .sessionManagement()            //Session controle concurence access
                    .maximumSessions(1)
                    .expiredUrl("/login?expired")
                    .sessionRegistry(sessionRegistry);
    
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
    
        //Session controle concurence access
        //http.sessionManagement().maximumSessions(1);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-18
      • 2014-09-22
      • 2012-01-25
      • 1970-01-01
      • 1970-01-01
      • 2016-02-11
      • 2012-04-05
      • 2016-04-22
      • 2014-04-16
      相关资源
      最近更新 更多