【问题标题】:Spring Security @PreAuthorize or @PreFilterSpring Security @PreAuthorize 或 @PreFilter
【发布时间】: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


    【解决方案1】:

    您可以通过执行以下操作来实现您想要的:

    @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);
        }
        
    }
    

    然后:

    @PreAuthorize("@mlpConfigService.ownedByUser(#mlpConfigId, authentication.name)")
    

    【讨论】:

    • 我会试试的。您认为这是最佳做法吗?
    • 我认为这对您的用例来说是一个干净的解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-13
    • 2016-07-18
    • 1970-01-01
    • 2015-04-23
    • 2015-07-30
    • 2021-06-28
    • 2016-04-16
    相关资源
    最近更新 更多