我在 Spring Boot 应用程序中使用 Spring Security 来提供用户功能。我花了一些时间寻找问题的答案,但只为使用基于 xml 的配置的人找到了解决方案。
我的设置与此非常相似:http://www.baeldung.com/spring-security-track-logged-in-users (底部的替代方法)。
这是我的安全配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().defaultSuccessUrl("/home.html", true)
//.and().exceptionHandling().accessDeniedPage("/home")
.and().authorizeRequests().antMatchers("/editor").hasAnyAuthority("SUPERUSER")
.and().authorizeRequests().antMatchers("/editor").hasAnyAuthority("ADMIN")
.and().authorizeRequests().antMatchers("/").permitAll().anyRequest().authenticated()
.and().formLogin().loginPage("/login").permitAll()
.and().authorizeRequests().antMatchers("/static/**").permitAll()
.and().logout().permitAll().logoutSuccessUrl("/login").logoutUrl("/logout").deleteCookies("JSESSIONID")
.and().csrf().disable();
http.sessionManagement().invalidSessionUrl("/login").maximumSessions(1).sessionRegistry(sessionRegistry()).expiredUrl("/login");
}
这是我调用 sessionRegistry 的地方:
public List<String> getAllLoggedUsernames() {
final List<Object> allPrincipals = sessionRegistry.getAllPrincipals();
// System.out.println("All Principals: " + sessionRegistry.getAllPrincipals());
List<String> allUsernames = new ArrayList<String>();
System.out.println(allUsernames.size());
for (final Object principal : allPrincipals) {
if (principal instanceof SecUserDetails) {
final SecUserDetails user = (SecUserDetails) principal;
//Make sure the session is not expired --------------------------------------------------▼
List<SessionInformation> activeUserSessions = sessionRegistry.getAllSessions(principal, false);
if (!activeUserSessions.isEmpty()) {
allUsernames.add(user.getUsername());
System.out.println(user.getUsername());
}
}
}
return allUsernames;
}
现在,当我尝试获取当前登录的用户时,我会正确地得到它:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName();
我的 sessionRegistry 按以下方式定义为 Bean:
@Bean
public SessionRegistry sessionRegistry() {
return new SessionRegistryImpl();
}
剩下要说的是,我通过类似这样的服务从 Controller 调用 getAllLoggedUsernames():
@Autowired
private SecUserDetailService service;
稍后在 @RequestMapping 函数中:
service.getAllLoggedUsernames();
无论有多少用户实际登录,收到的列表始终为空。
现在,我从这里提出的其他问题中猜测,不知何故,我的应用程序被加载了两次,或者我的 bean 设置被搞乱了。我认为 @Autowired 不起作用,因为我认为服务需要某种上下文信息?
不过,我对依赖注入(inject)还很陌生,所以很难让一切都正确。
感谢您提前提供的任何帮助!
编辑 - 次要澄清
最佳答案
已解决:存在类型错误,getAllLoggedUsers()
方法中的 if 语句始终解析为 false,因为该对象不是我自己的 UserDetails 类的实例,而是 org.springframework.security.core.userdetails.User 的实例!
关于java - Spring boot sessionRegistry 返回空的主体列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45347583/