2013-07-24 107 views
3

我是Spring MVC和Spring Security的新手。我已經使用Spring安全性和MVC執行了登錄和註冊功能。我無法找到任何會議管理的方式。從Spring Session中獲取用戶詳細信息

我想訪問像(電子郵件,名稱,ID,角色等)的所有頁面上的一些用戶的詳細信息。 我想將這些保存到會話對象,以便我可以在任何頁面上獲得這些內容。

我碰到下面的方式進行會話春季

Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
auth.getPrincipal(); 

但是從這個返回的對象,我可以得到唯一的用戶名和密碼信息。

但我需要訪問該用戶的更多細節。

  • 有沒有辦法通過將它保存到會話和獲取jsp頁面來做到這一點?
  • 或者是否有任何OOTB方式在春天完成這項工作?

請幫我解決這個問題。 在此先感謝。我想要從SecurityContextHolder.getContext()。getAuthentication()。getDetails();返回我的模型類對象。爲此我需要配置。

問候, Pranav

+0

如果你得到了用戶名無法您的用戶名查詢?我假設你用來保存用戶信息的表中有用戶名(這是唯一的)。手動或通過ORM查詢並映射到用戶模型對象。 – justin

回答

2

你可以用這個來獲得UserDetails(或任何實現您的自定義細節)。

UserDetails userDetails = SecurityContextHolder.getContext().getAuthentication().getDetails(); 

如果不存在,您可以從UserDetailsService加載用戶詳細信息。

在這兩種情況下,我認爲你必須將它們自己保存在會話作用域bean中。

+0

我想讓我的模型類對象從SecurityContextHolder.getContext()。getAuthentication()。getDetails();返回。爲此我需要配置 –

5

你需要讓你的模型類實現UserDetails接口

class MyUserModel implements UserDetails { 
    //All fields and setter/getters 

    //All interface methods implementation 
} 

然後在你的春天控制器,你可以這樣做:

Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
Object myUser = (auth != null) ? auth.getPrincipal() : null; 

if (myUser instanceof MyUserModel) { 
    MyUserModel user = (MyUserModel) myUser;  
    //get details from model object   
} 
相關問題