這是我的端點,它在登錄時回傳我的電子郵件地址
@GetMapping("/user")
public String userInfo(Authentication authentication) {
String userName = authentication.getName();
return userName;
}
我想給createdBy變數這個值
@PostMapping("/request")
public RequestDTO saveRequest(@RequestBody final RequestDTO requestDTO) {
requestDTO.setCreatedBy(InsertTheNewStringVariableHere);
return requestUseCase.createRequest(requestDTO);
}
uj5u.com熱心網友回復:
假設您在兩個端點都進行了身份驗證,您可以簡單地Authentication在第二個端點中添加一個引數:
@PostMapping("/request")
public RequestDTO saveRequest(@RequestBody final RequestDTO requestDTO,
Authentication authentication) {
requestDTO.setCreatedBy(authentication.getName());
return requestUseCase.createRequest(requestDTO);
}
uj5u.com熱心網友回復:
這完全取決于您如何訪問您的rest api.
如果你擁有代碼,我的意思是如果你的類在同一個專案中,你可以這樣做:
@PostMapping("/request")
public RequestDTO saveRequest(@RequestBody final RequestDTO requestDTO) {
requestDTO.setCreatedBy(yourServiceInstance.userInfo(authentication));
return requestUseCase.createRequest(requestDTO);
}
如果是外部的api,則必須從以下位置呼叫該服務http client:
@PostMapping("/request")
public RequestDTO saveRequest(@RequestBody final RequestDTO requestDTO) {
requestDTO.setCreatedBy(yourHttpClient.callUserInfo(authentication));
return requestUseCase.createRequest(requestDTO);
}
您將在類中注入您的userInfo物件和一個Authentication物件。
uj5u.com熱心網友回復:
您也可以使用 SecurityContextHolder
@PostMapping("/request")
public RequestDTO saveRequest(@RequestBody final RequestDTO requestDTO) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
requestDTO.setCreatedBy(authentication.getName());
return requestUseCase.createRequest(requestDTO);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/336705.html
下一篇:在陣列python中創建陣列
