How can I have list of all users logged in (via spring security) my web application

后端 未结 7 2267
独厮守ぢ
独厮守ぢ 2020-11-27 12:27

I\'m using spring security in my web application, and now I want to have a list of all users who are logged in my program.

How can I have access to that list? Aren\'

相关标签:
7条回答
  • 2020-11-27 12:49

    Similar to @rolyanos solution, mine for me always works:

    - for the controller

    @RequestMapping(value = "/admin")
    public String admin(Map<String, Object> model) {
    
        if(sessionRegistry.getAllPrincipals().size() != 0) {
            logger.info("ACTIVE USER: " + sessionRegistry.getAllPrincipals().size());
            model.put("activeuser",  sessionRegistry.getAllPrincipals().size());
        }
        else
            logger.warn("EMPTY" );
    
        logger.debug(log_msg_a + " access ADMIN page. Access granted." + ANSI_RESET);
        return "admin";
    }
    

    - for the front end

    <tr th:each="activeuser, iterStat: ${activeuser}">
        <th><b>Active users: </b></th> <td align="center" th:text="${activeuser}"></td>
        </tr>
    

    - for spring confing

    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }
    
    @Bean
    public ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisher() {
        return new ServletListenerRegistrationBean<HttpSessionEventPublisher>(new HttpSessionEventPublisher());
    }
    
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
        http.logout()
        .logoutSuccessUrl("/home")
        .logoutUrl("/logout")
        .invalidateHttpSession(true)
        .deleteCookies("JSESSIONID");
    
    
        http.authorizeRequests()
        .antMatchers("/", "/home")
        .permitAll()
    
        .antMatchers("/admin")
        .hasRole("ADMIN") 
        .anyRequest()
        .authenticated()
    
        .and()
        .formLogin()
        .loginPage("/home")
        .defaultSuccessUrl("/main")
        .permitAll()
        .and()
        .logout()
        .permitAll();
    
        http.sessionManagement().maximumSessions(1).sessionRegistry(sessionRegistry());
    
        http.authorizeRequests().antMatchers("/webjars/**").permitAll();
    
        http.exceptionHandling().accessDeniedPage("/403");
    }
    
    0 讨论(0)
提交回复
热议问题