1 回答
TA貢獻1831條經驗 獲得超4個贊
我會創建一個自定義Authentication對象并在其中存儲所需的信息。
對于用戶相關的數據,存儲在其內部Principal。對于非用戶相關的數據,聽起來Details是一個存儲的好地方。
許多內置函數AuthenticationProvider會創建一個UserDetails并存儲到Principal. UserDetails這意味著如果您正在使用那些內置的,您可以考慮只創建一個 customsied AuthenticationProvider。
因此,根據您實現身份驗證邏輯的方式,您需要自定義相關AuthenticationProvider等Filter。目的是訪問HttpServletRequest,從 HTTP 標頭獲取 JWT,解析 JWT,設置和配置此自定義Authentication對象并將其設置為SecurityContext:
SecurityContextHolder.getContext().setAuthentication(authenication);
Authentication要在 Controller 中訪問此對象,您可以使用:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
CurrentUser user = (CurrentUser) auth.getPrincipal();
CurrentRequestDetail detail= (CurrentRequestDetail) auth.getDetails();
/** CurrentUser and CurrentRequestDetail is the customised Principal and Details**/
如果您只需要訪問 [ Principal],您可以使用@AuthenticationPrincipal:
@PostMapping("")
public Mono<User> login(@RequestBody User post,
@RequestParam String user_id,
@RequestParam String username,
@AuthenticationPrincipal CurrentUser currentUser) {
//Need to access information from JWT claims here
return this.repository.findById(user_id);
}
添加回答
舉報
