我在我的spring引导应用程序中使用spring安全性来提供用户功能。我花了一些时间寻找解决方案的答案,但只找到了使用基于xml的配置的人的解决方案。Spring引导sessionRegistry返回主体的空列表
我的设置与此非常相似:http://www.baeldung.com/spring-security-track-logged-in-users(底部的替代方法)。
这是我SecurityConfiguration:
@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();
}
它留给说我通过很多这样的服务调用从控制器getAllLoggedUsernames():
@Autowired
private SecUserDetailService service;
,后来在一个@RequestMapping功能:
service.getAllLoggedUsernames();
而收到的名单是总是空的,不管有多少用户实际登录。
现在我从其他问题的问题在这里问我的猜测是,我的应用程序被加载两次或我的bean设置搞砸了。我认为@Autowired不起作用,因为我认为服务需要某种上下文信息?
虽然我真的很依赖注入依赖注入,所以它很难让一切正确。
感谢您提前提供任何帮助!
编辑 - 未成年人澄清
什么是你的'sesionRegistry()'方法做... –
恐怕我不知道你的意思,因为我没有在我的代码中调用sessionRegistry()方法。你的意思是'getPrincipals()'方法吗? –
然后''sessionRegistry()'方法来自哪里,你在你的配置中使用它。 –