【发布时间】:2020-10-15 05:28:57
【问题描述】:
最近我发现有一种方法可以使用 Spring Security 对方法进行预授权。但我不确定我是否可以通过这些注释实现我想要的。
@DeleteMapping("/delete/{configId}")
public ResponseEntity<Object> deleteMlpConfig(@RequestHeader HttpHeaders headers,
@PathVariable("configId") long mlpConfigId, Authentication authentication) {
MlpConfig config = mlpConfigService.findById(mlpConfigId);
User user = userService.findByUsername(authentication.getName());
if (config.getUser().equals(user)) {
mlpConfigRepository.delete(config);
return ResponseEntity.ok(new MessageResponse("Configuration removed successfully!"));
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Error: Unauthorized");
}
}
你可以看到这个 if 子句。这个 if 子句应该是一个预授权。只有请求此删除命令的用户拥有此配置,他才应该能够调用该方法。
有问题的是前端只将 id 发送到已删除的配置,并且必须加载配置以检查我猜的任何内容。所以这样的事情在这里不起作用:
@PreAuthorize("#config.user == authentication.id")
我可以使用 preAuthorize 处理它吗?或者这里的最佳做法是什么?
【问题讨论】:
标签: java spring-boot spring-security