如何从spring security 3.1获取当前用户角色

Bha*_*has 22 spring spring-security

我已从数据库中为当前用户加载了角色.我可以在jsp中使用spring security表达式访问用户角色,并且可以隐藏未经hasRole授权的选项和URL.现在我想将它放在servlet中并将其显示在日志中.(或存储在用户对象会话中).我们怎样才能实现它?

Dan*_*ani 63

你可以尝试这样的事情:

Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>)    SecurityContextHolder.getContext().getAuthentication().getAuthorities();
Run Code Online (Sandbox Code Playgroud)

您拥有authority变量中的角色集合.

更新:修复了GrantedAuthority泛型的错误

  • 您应该使用此列表中的授权授权接口,因为授权提供程序之间的实现可能不同 (2认同)
  • 如果你这样做会有一个未经检查的情况但是你可以通过将集合类型设置为:Collection <?来避免这种情况.扩展GrantedAuthority> (2认同)

小智 21

如果您使用Java 8开发,它会变得更容易.

要获得所有用户角色:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

Set<String> roles = authentication.getAuthorities().stream()
     .map(r -> r.getAuthority()).collect(Collectors.toSet());
Run Code Online (Sandbox Code Playgroud)

检查用户是否具有特定角色,例如ROLE_USER:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

boolean hasUserRole = authentication.getAuthorities().stream()
          .anyMatch(r -> r.getAuthority().equals("ROLE_USER"));
Run Code Online (Sandbox Code Playgroud)


max*_*dim 8

你试过从HttpServletRequest 调用getUserPrincipal()吗?

  • 很公平.快速说明:Dani的方法存在将代码与Spring安全实现耦合的缺点,而getUserPricipal()是servlet规范中的标准调用,应该适用于任何提供程序. (7认同)
  • 使用getUserPrincipal(),您只能获得请求者的名称.我认为问题是如何获得分配给该用户的角色,所以我猜在getUserPrincipal()中也不会以这种方式工作. (3认同)