这是我的端点,当我登录时它返回我的电子邮件地址
@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);
}
假设您在两个端点都进行了身份验证,您可以简单地在第二个端点中添加Authentication
作为参数:
@PostMapping("/request")
public RequestDTO saveRequest(@RequestBody final RequestDTO requestDTO,
Authentication authentication) {
requestDTO.setCreatedBy(authentication.getName());
return requestUseCase.createRequest(requestDTO);
}
这完全取决于你如何访问你的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
对象。
您也可以使用SecurityContextHolder
@PostMapping("/request")
public RequestDTO saveRequest(@RequestBody final RequestDTO requestDTO) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
requestDTO.setCreatedBy(authentication.getName());
return requestUseCase.createRequest(requestDTO);
}