1 回答

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超4個贊
我會創(chuàng)建一個自定義Authentication
對象并在其中存儲所需的信息。
對于用戶相關(guān)的數(shù)據(jù),存儲在其內(nèi)部Principal
。對于非用戶相關(guān)的數(shù)據(jù),聽起來Details
是一個存儲的好地方。
許多內(nèi)置函數(shù)AuthenticationProvider
會創(chuàng)建一個UserDetails
并存儲到Principal
. UserDetails
這意味著如果您正在使用那些內(nèi)置的,您可以考慮只創(chuàng)建一個 customsied AuthenticationProvider
。
因此,根據(jù)您實(shí)現(xiàn)身份驗(yàn)證邏輯的方式,您需要自定義相關(guān)AuthenticationProvider
等Filter
。目的是訪問HttpServletRequest
,從 HTTP 標(biāo)頭獲取 JWT,解析 JWT,設(shè)置和配置此自定義Authentication
對象并將其設(shè)置為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);
}
添加回答
舉報