我已经从数据库中为当前用户加载了角色。我可以在JSP中使用spring安全表达式来访问用户角色,并且可以隐藏未被hasRole授权的选项和URL。现在,我希望将它放在servlet中,并在日志中显示它(或存储在用户对象会话中)。我们如何才能做到这一点?
发布于 2012-04-10 17:15:10
您可以尝试如下所示:
Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
您在权限变量中有角色的集合。
发布于 2017-03-21 21:17:59
如果在Java 8上进行开发,就会变得更容易。
要获取所有用户角色:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Set<String> roles = authentication.getAuthorities().stream()
.map(r -> r.getAuthority()).collect(Collectors.toSet());
检查用户是否具有特定角色,例如ROLE_USER
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
boolean hasUserRole = authentication.getAuthorities().stream()
.anyMatch(r -> r.getAuthority().equals("ROLE_USER"));
发布于 2012-04-10 17:11:08
尝试从HttpServletRequest调用getUserPrincipal()。
https://stackoverflow.com/questions/10092882
复制相似问题