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