簡體   English   中英

如何在 Spring Boot 中找出當前登錄的用戶?

[英]How to find out the currently logged-in user in Spring Boot?

這個 Spring Boot 應用程序中有一個 Web 服務,它為登錄用戶返回一些數據:

@RequestMapping("/resource")
public Map<String, Object> home() {
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("id", UUID.randomUUID().toString());
    model.put("content", "Hello World");
    return model;
}

想象一下,該方法的返回值取決於當前登錄的用戶。

我怎樣才能知道哪個用戶登錄了該方法?

按要求:

內部使用Spring Security 的Spring Boot 提供了一個SecurityContextHolder類,它允許通過以下方式查找當前經過身份驗證的用戶:

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

身份驗證實例現在提供以下方法:

  • 獲取登錄用戶的用戶名: getPrincipal()
  • 獲取認證用戶的密碼: getCredentials()
  • 獲取已認證用戶的分配角色: getAuthorities()
  • 獲取經過身份驗證的用戶的更多詳細信息: getDetails()

從 Spring Security 3.2 開始,您可以通過在控制器方法中添加參數來獲取當前登錄的用戶(您的UserDetails實現):

import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;

@RequestMapping("/resource")
public Map<String, Object> home(@AuthenticationPrincipal User user) {
   ..
}

User替換為實現UserDetails接口的類的名稱。

編輯

由於 Spring Security 4.0 注釋被移動到一個不同的包:

import org.springframework.security.core.annotation.AuthenticationPrincipal;

附錄

即使在WebFlux反應式環境中,這也可以工作,而SecurityContextHolder.getContext().getAuthentication()由於范式從每個請求模型的線程轉移到每個線程的多個請求而不起作用。

您也可以簡單地使用 HttpServletRequest 來獲取用戶原則,

使用 HttpServletRequest 請求,

String user=request.getUserPrincipal().getName();

一種方法是將java.security.Principal添加為參數,如下所示:

@RequestMapping("/resource")
public Map<String, Object> home(Principal principal) {
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("id", UUID.randomUUID().toString());
    model.put("content", "Hello " + principal.getName());
    return model;
}

從 5.2 版開始,您可以使用CurrentSecurityContext注釋:

@GetMapping("/hello")
public String hello(@CurrentSecurityContext(expression="authentication?.name")
                    String username) {
    return "Hello, " + username + "!";
}

在 Spring boot v2.1.9.RELEASE 中,如果您嘗試獲取姓名、電子郵件、given_name,您可以從 Pricipal 獲取這些詳細信息。 注意:我在 google oauth2 中使用 spring security

Map<String , Object> userDetails = ((DefaultOidcUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getAttributes(); System.out.println(userDetails.get("name")); System.out.println(userDetails.get("email")); System.out.println(userDetails.get("given_name"));

最近使用 Keycloak 身份驗證服務器並訪問當前登錄的用戶數據可以這樣訪問

String userID;

KeycloakPrincipal kcPrincipal = getPrincipal();
KeycloakSecurityContext ksContext = kcPrincipal.getKeycloakSecurityContext();
IDToken idToken = ksContext.getToken();
userID = idToken.getName();

我使用帶有 OAuth 的 spring boot 2.0 所以我這樣做

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Object pricipal = auth.getPrincipal();
String user="";
if (pricipal instanceof DefaultOidcUser) {
       user = ((DefaultOidcUser) pricipal).getName();
}

您可以在不使用任何 spring 安全功能的情況下找到當前登錄的用戶名。 您只需要一個 jdk 1.8

請執行下列操作 :

@RequestMapping("/login")
@Override
public ModelAndView AuthChecker(@RequestParam("email") String email, @RequestParam("password") String password, Customers cust) {

     ModelAndView mv = new ModelAndView("index");
     if((repo.findByEmail(email)!=null) && (repo.findByPassword(password)!=null)) {
        
         
      List<Customers> l=  repo.findAll();
      
      cust = (Customers) l.stream() 
      .filter(x -> email.equals(x.getEmail()))        
      .findAny()                                      
      .orElse(null); 
    
        mv.addObject("user",cust.getName());
         mv.setViewName("DashBoardRedirect");
    
         return mv;

成功獲取名稱后,您可以在任何 jsp/thymeleaf 視圖中使用相同的名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM