Spring MVC Interceptor exclude paths on HTTP method

Viewed 1694

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.

1 Answers
Related