1

我想将 Spring 安全应用程序切换到注释,但我想确保每个请求都有自己的@PreAuthorize注释,然后才允许在外部调用它。

是否可以为此设置 Spring Security 策略?

4

1 回答 1

3

据我所知,没有办法定义这种政策。

但是您可以设置一个 Spring MVC 拦截器,它将在运行时检查相应处理程序方法上是否存在 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);
            if (annotation == null) {
                // prevent access to method wihout security restrictions
                throw new RuntimeException("Rights are not defined for this handler");
            }

        }
        return true;
    }
.....
}
于 2013-03-05T17:02:31.037 回答