Reputation: 1794
Recently I found out that there is a way to preAuthorize methods with Spring Security. But I'm not sure if I can achieve what I want with this annotations.
@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");
}
}
You can see this if-clause. This if-clause should be a preAuthorization. Only if the user who requests this delete command owns this config he should be able to even call the method.
The problematic thing is that the frontend only sends the id of the to deleted config and the config has to be loaded to check anything I guess. So something like this here does not work:
@PreAuthorize("#config.user == authentication.id")
Can I handle it with preAuthorize or what would be best practice here?
Upvotes: 2
Views: 1411
Reputation: 4475
you can achieve what you want by doing the following:
@Service
public class MlpConfigService {
@Transactional
public boolean ownedByUser(Long mlpConfigId, String name){
MlpConfig config = mlpConfigService.findById(mlpConfigId);
User user = userService.findByUsername(name);
return config.getUser().equals(user);
}
}
and then:
@PreAuthorize("@mlpConfigService.ownedByUser(#mlpConfigId, authentication.name)")
Upvotes: 3