2017-03-16 47 views
1

基於我的理解,在Spring Security中有多種不同的方式來檢索經過身份驗證的用戶名。在Spring Security中存儲用戶對象

我目前由包括Principal作爲控制器方法參數抓住了用戶名:

@RequestMapping(value = "/dashboard", method = RequestMethod.GET) 
public ModelAndView displayHomePage(ModelAndView modelAndView, Principal principal) { 

    modelAndView.addObject("email", principal.getName()); 

    // Render template located at src/main/resources/templates/dashboard.html 
    modelAndView.setViewName("dashboard"); 

    return modelAndView; 
} 

春天在什麼安全提供了一種簡單的方法對我來說,用戶對象存儲到會話中,因此它可以很容易地通過任何控制器方法檢索?

我想避免每次執行DB查詢:

// Lookup user in database by e-mail 
User user = userService.findUserByEmail(principal.getName()); 

我使用的Spring Security 4.2。

+0

@MatejMarconak任何控制器方法檢索 –

+2

你可以做這樣的事情:'認證認證= SecurityContextHolder.getContext()getAuthentication(); String currentPrincipalName = authentication.getName();' –

+0

好的,但是如何在不執行數據庫查找的情況下獲取整個User對象呢?我已經更新了我的問題,以便更清楚。 –

回答

3

的Spring Security提供了一個靜態方法可以快速,方便地訪問:

Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
String name = auth.getName(); 

或者

User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 
String name = user.getUsername(); 

也許你想在一個抽象基類來完成此

public abstract class BaseController { 
    protected User getCurrentUser() { 
     return (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 
    } 
} 
... 
public YourController extends BaseController { 
... 
} 

更新

如果您想在會話中存儲當前經過身份驗證的用戶,則只需按照@gkatzioura的建議,首次將對象存儲在對象中。

@Component 
@Scope("session") 
public class MySessionInfo { 

    private User user; 

    protected User getCurrentUser() { 
     if (user == null) { 
      user = userService.findUserByEmail(SecurityContextHolder.getContext().getAuthentication().getPrincipal().getName()); 
     } 
     return user; 
    } 
} 

你可以注入這個bean在你的控制器一樣

@Autowired 
private MySessionInfo mySessionInfo; 

在不登錄的用戶必須小心有關情況,但這是另外一個問題。

+0

如何根據控制器中該用戶的權限添加權限? –

0

您可以隨時使用spring security提供的方法來獲取基本信息,如名稱,權限和Authentication.class提供的所有內容。

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

但是,如果你想要更多的信息,使用會話bean來存儲信息也是一個好主意。

@Component 
@Scope("session") 
public class UserInfo { .. }