如何要求Spring应用程序中的所有请求处理程序都具有@PreAuthorize [英] How can I require that all request handlers in my Spring application have @PreAuthorize
本文介绍了如何要求Spring应用程序中的所有请求处理程序都具有@PreAuthorize的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将Spring安全应用程序切换到注释,但是我想确保每个请求在允许从外部调用之前都具有自己的 @PreAuthorize
注释.
I'd like to switch a Spring security application over to annotations, but I want to make sure that every request has its own @PreAuthorize
annotation before allowing it to be called externally.
是否可以为此设置Spring Security?
Is it possible to set Spring Security up with a policy for this?
推荐答案
据我所知,没有办法定义这种策略.
As far as I know there is no way to define such kind of policy.
但是您可以设置一个Spring MVC拦截器,该拦截器将在运行时检查相应处理程序方法上PreAuthorize批注的存在:
But you can set up an Spring MVC interceptor that will check presence of PreAuthorize annotation on corresponding handler method at run time:
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);
if (annotation == null) {
// prevent access to method wihout security restrictions
throw new RuntimeException("Rights are not defined for this handler");
}
}
return true;
}
.....
}
这篇关于如何要求Spring应用程序中的所有请求处理程序都具有@PreAuthorize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文