Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC Interceptor exclude paths on HTTP method

I have some interceptors that need to check the headers and the authorization in some requests done to my API. For example, some requests should require user authentication (for example, to alter user details from the database) and some don't require authentication (for example, to create a user). Unfortunately, the methods for excluding paths from the interceptors don't depend on the request method.

Right now I have created an Util class that receives an array of strings of paths and methods that should be excluded from the verifications. For example: "POST /api/users" should not be intercepted by my authentication interceptor because it is for creating a user, but "PUT /api/users" should be intercepted because it is for altering an existing user (who should be logged in).

public static Boolean skipVerification(HttpServletRequest request, String... skipRequests) {
    for (String string : skipRequests) {
        String[] split = string.split(" ");
        if(split[0].equals(request.getMethod()) && split[1].equals(request.getRequestURI()))
            return true;
    }
    return false;
}

In the constructor of my interceptor, I add the requests that should be skipped and in the PreHandle method I return true if the request matches any one of them as they didn't need to me intercepted in the first place.

public AuthenticationHeaderInterceptor(String...skipWhen) {
    this.skipWhen = skipWhen;
}

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

    if(InterceptorUtils.skipVerification(request, skipWhen))
        return true;

///Do Authentication Logic

}

I know that changing the URI for creating and editing users would solve this, but I prefer not to clutter my API with too many URIs and was wondering if there was a cleaner way to solve this.

like image 998
davilimap Avatar asked Nov 08 '22 18:11

davilimap


1 Answers

Looking at the code, I was checking if you would be able to extend InterceptorRegistry, InterceptorRegistration, and MappedInterceptor. You would also have to extend PathMatcher and incorporate code to check methods as well as paths, which PathMatcher isn't meant for. So overall, the way you are doing it currently is probably best. I would also point out the code in Spring's AntPathMatcher has always been very messy and buggy so you probably wouldn't want to take on any task that involved dealing with it.

like image 161
Dave L. Avatar answered Nov 14 '22 21:11

Dave L.