2012-04-10 132 views
17

我已经从当前用户的数据库加载角色。我可以通过jsp中的spring security表达式访问用户角色,并且可以隐藏未经hasRole授权的选项和url。现在我想把它放在servlet中并显示在日志中(或存储在用户对象会话中)。我们如何实现它?如何从spring安全中获取当前用户角色3.1

回答

53

你可以尝试这样的事情:

Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities(); 

你的角色在变当局收集。

更新:的GrantedAuthority的固定错字通用

+0

感谢Dani它为我工作。 – Bhas 2012-04-10 19:35:56

+1

不用理睬;) – Dani 2012-04-10 19:43:14

+2

您应该在此列表中使用grantedauthority接口,因为授权提供者之间的实现可能有所不同 – Laures 2012-04-11 05:26:05

7

您是否试过从HttpServletRequest调用getUserPrincipal()

+0

感谢您的答复,我没有尝试,但我已经实现什么达尼告诉,它为我工作。 – Bhas 2012-04-10 19:36:50

+7

够公平的。快速提示:Dani的方法存在将代码与Spring安全性实现耦合的缺点,而getUserPricipal()是servlet规范中的标准调用,应该与任何提供者协同工作。 – maximdim 2012-04-10 20:37:31

+3

使用getUserPrincipal(),您只能获取请求者的名称。我认为问题是如何获得分配给该用户的角色,所以我猜getUserPrincipal()不会以这种方式工作。 – Jay 2015-07-13 14:07:24

2

要完成两个答案...

这里是一个getUserPrincipal安全Spring实现,所以你可以看到,实际上getUserPrincipal我们SecurityContextHolder

public Principal getUserPrincipal() { 
     Authentication auth = getAuthentication(); 

     if ((auth == null) || (auth.getPrincipal() == null)) { 
      return null; 
     }  
     return auth; 
} 

//And the getAuthentication 
private Authentication getAuthentication() { 
    Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 

    if (!trustResolver.isAnonymous(auth)) { 
     return auth; 
    } 
    return null; 
} 
6

如果您使用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")); 
0

高清springSecurityService

DEF角色= springSecurityService.getAuthentication()getAuthorities()

+2

请尝试提供更广泛和格式化的答案。你可以检查[我如何写出一个好的答案?](https://stackoverflow.com/help/how-to-answer)。 – 2017-08-16 08:11:59

相关问题