我在 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();
}
剩下要说的是,我通过如下服务从控制器调用getAllLoggedUsernames():
@Autowired
private SecUserDetailService service;
稍后在@RequestMapping 函数中:
service.getAllLoggedUsernames();
并且那里收到的列表总是空的,不管有多少用户实际登录。
现在,我从这里提出的其他问题中猜测,我的应用程序以某种方式加载了两次,或者我的 bean 设置搞砸了。我有点认为 @Autowired 不起作用,因为我认为服务需要某种上下文信息?
不过,我对依赖注入真的很陌生,所以很难让一切都正确。
提前感谢您的任何帮助!
编辑 - 小说明
已解决:出现类型错误,方法中的 if 语句getAllLoggedUsers()
总是解析为 false,因为 Object 不是我自己的 UserDetails 类的实例,而是 org.springframework.security.core.userdetails.User 的实例!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句