【问题标题】:Spring boot @PreAuthorize (is it possible to modify the input to the method in @PreAuthorize then pass into the method)Spring boot @PreAuthorize(是否可以修改@PreAuthorize中方法的输入然后传递给方法)
【发布时间】:2021-04-27 11:19:07
【问题描述】:

我有一个用 @PreAuthorize(...) 注释的方法,其中一些逻辑消失了,并查询 API 以获取有关用户可以查看的一些信息。但是,我有这个端点,我需要将这个 @PreAuthorize 注释添加到其中接收一个更“复杂”的对象,我想稍微转换(该对象包含一个数组,在某些情况下我想从中添加/删除数据) .

@PostMapping("/search")
@PreAuthorize("@Service.isAuth(#searchParam)")
public ResponseEntity<Response> search(SearchParams searchParam) {
    return service.getSearchResult(searchParam);
}

有没有办法我可以在@PreAuthorize 注释中修改searchParam,然后将其传递到方法体中,我知道这可能不是正确的方法,也可能不是@PreAuthorize不是为此而设计的,但即使使用不同类型的注释也有任何方法可以做到这一点。显然在最坏的情况下,我可以将逻辑移到方法主体中,但如果可能的话,我更愿意使用像 @PreAuthorize 提供的基于注释的解决方案。感谢您提供任何帮助,即使指向其他相关内容的链接也会很有用,我在 google 上没有找到很多与此相关的内容。

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    我认为最好的解决方案是制作一个处理程序/拦截器,然后用 @PreAuthorize 对其进行注释。所以我认为你在正确的轨道上,但你需要确保你修改你的代码来实现 HandlerMapping 接口来创建拦截器,然后覆盖 prehandle 方法。在您需要以编程方式使用 @PreAuthorize 对其进行注释之后。最后一件事是使用包装器来修改 HttpWrapper,它不能手动完成。这里按顺序链接到相关资源:

    试一试,希望能成功。

    取自第二个链接的代码片段使用程序化的 PreAuthorize 而不是注释:

    public class PreAuthorizeChecker implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            PreAuthorize annotation = AnnotationUtils.findAnnotation(hm.getMethod(), PreAuthorize.class);
    //TODO use the technique shown on the third link to wrap and modify the HttpServletRequest
            if (annotation == null) {
                // prevent access to method wihout security restrictions
                throw new RuntimeException("Rights are not defined for this handler");
            }
    
        }
        return true;
    }
    

    .....

    【讨论】:

      猜你喜欢
      • 2014-09-13
      • 1970-01-01
      • 2013-08-30
      • 2011-03-06
      • 2016-04-16
      • 2018-07-27
      • 1970-01-01
      • 2015-03-25
      相关资源
      最近更新 更多