2017-06-04 69 views
0

在使用Mongodb JWT的Jhipster 4.4.1應用程序中。 我需要查詢登錄的用戶,我不知道我怎麼可以在Java控制器(資源) 在SecurityUtils我不知道如何獲取ID用戶已登錄(ID),返回。 Jhipster 4.1.1

public static String getCurrentUserLogin() { 
    SecurityContext securityContext = SecurityContextHolder.getContext(); 
    Authentication authentication = securityContext.getAuthentication(); 
    String userName = null; 
    if (authentication != null) { 
     if (authentication.getPrincipal() instanceof UserDetails) { 
      UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); 
      userName = springSecurityUser.getUsername(); 
     } else if (authentication.getPrincipal() instanceof String) { 
      userName = (String) authentication.getPrincipal(); 
     } 
    } 
    return userName; 
} 

我可以捕獲檢索用戶ID登錄,而不諮詢數據庫。

謝謝

回答

2

如果您需要在當前用戶,然後你就可以查詢logingetCurrentUserLogin()你的問題給出的,因爲它是unique反正。

如果你確實需要ID,那麼戳一下AccountResource,你會發現UserDTOUser有一個.getID()方法。

+0

對我來說,在我的資源中,這行代碼允許我獲取當前登錄用戶的ID。我只是不是100%確定,如果這是/是如何做到這一點的正確方法: Long id = userService.getUserWithAuthoritiesByLogin(SecurityUtils.getCurrentUserLogin())。get()。getId(); – ivo