Home > Software design >  How to check HTTP request header for certain endpoints in Spring Framework
How to check HTTP request header for certain endpoints in Spring Framework

Time:11-20

I have a simple Spring Boot REST service for the IFTTT platform. Each authorized request will contain a header IFTTT-Service-Key with my account's service key and I will use that to either process the request or return a 401 (Unauthorized). However, I only want to do this for select endpoints -- and specifically not for ANY of the Spring actuator endpoints.

I have looked into Spring Security, using filters, using HandlerInterceptors, but none seem to fit what I am trying to do exactly. Spring security seems to come with a lot of extra stuff (especially the default user login), filters don't really seem to match the use case, and the handler interceptor works fine but I would have to code logic in to watch specific URLs and ignore others.

What is the best way to achieve what I am trying to do?

For reference, this is the code I have now:

public class ServiceKeyValidator implements HandlerInterceptor {
    private final String myIftttServiceKey;

    public ServiceKeyValidator(@Value("${ifttt.service-key}") String myIftttServiceKey) {
        this.myIftttServiceKey = myIftttServiceKey;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // TODO will have to put logic in to skip this when actuator endpoints are added

        String serviceKeyHeader = request.getHeader("IFTTT-Service-Key");

        if (!myIftttServiceKey.equals(serviceKeyHeader)) {
            var error = new Error("Incorrect value for IFTTT-Service-Key");
            var errorResponse = new ErrorResponse(Collections.singletonList(error));
            throw new UnauthorizedException(errorResponse);
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}

CodePudding user response:

You need to add filtering for the required endpoints in the place where you register your HandlerInterceptor.

For example:

@EnableWebMvc
@Configuration
public class AppConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(
            new ServiceKeyValidator())
                .addPathPatterns("/ifttt/**")
                .excludePathPatterns("/actuator/**");
    }

}

You can use different URLs path matchers to filter which URL endpoints must be handled by your interceptor and which are not. As the method addPathPatterns returns InterceptorRegistration object that configures this.

  • Related