Spring boot@PreAuthorize(是否可以在@PreAuthorization中修改方法的输入,然后传递



我有一个用@PreAuthorize(…(注释的方法,该方法带有一些逻辑,该逻辑会离开并查询API以获取有关用户可以查看的内容的信息。然而,我有一个端点,我需要将@PreAuthorize注释添加到其中,该注释在一个更";复数";对象(该对象包含一个数组,在某些情况下我想从中添加/删除数据(。

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

有没有一种方法可以修改@PreAuthorize注释中的searchParam,然后将其传递到方法体中,我知道这可能不是正确的方法,也可能不是@PreAuthorization设计的目的,但即使使用不同类型的注释,也有什么方法可以做到这一点。显然,在最坏的情况下,我可以将逻辑移动到方法体中,但如果可能的话,我更喜欢使用@PreAuthorize提供的基于注释的解决方案。谢谢你的任何帮助,即使是其他相关内容的链接也会很有用。我在谷歌上没有发现太多与此相关的内容。

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

  • 创建处理程序/拦截器:https://www.baeldung.com/spring-mvc-handlerinterceptor

  • 在拦截器中使用PreAuthorize:我怎么能要求Spring应用程序中的所有请求处理程序都有@PreAuthorize

  • 要修改HttpServlet请求,您需要一个包装器:如何在java中修改HttpServlet request主体?

试试看,希望能奏效。

从第二个链接获取的代码段使用程序化的预授权而不是注释:

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

相关内容

最新更新