简体   繁体   中英

Spring Security @PreAuthorize or @PreFilter

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?

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)")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM