2012-04-10 138 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

相關問題