Skip to content

Lab M03P01

This lab demonstrates implementation of custom security filter for x-apikey HTTP header verification. The filter is then configured in SecurityFilterChain.

  1. There is ApiKeyFilter class skeleton, which needs implementation. As first step let's use existing abstract class OncePerRequestFilter and extend the ApiKeyFilter from it. The OncePerRequestFilter should guarantee a single execution per request dispatch. Now you need to implement the doFilterInternal() method, which defines attributes of type HttpServletRequest, HttpServletResponse, and FilterChain.

  2. Add implementation of doFilterInternal(), which retrieve value of x-apikey HTTP header from request and compares it with expected value. For sake of simplicity, there is hardcoded expected API key value defined. The filter logic should be as follows:

    • If there is no x-apikey, or the value does not match with expected one set the HTTP status code of response to 401, and write some error message into response body. Next filter in chain should not be invoked.

      Hint-1:

         response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      
      Hint-2:
         PrintWriter writer = response.getWriter();
         writer.print("{\"message\":\"Invalid API Key\"}");
         writer.flush();
         writer.close();
      
      * If the x-apikey is validated successfully, just invoke next filter in chain. Hint: filterChain.doFilter(request, response);

  3. You need to add newly implemented filter into SecurityFilterChain. Open SecuritConfig class and locate the securityFilterChain() method. Spring enables to add filter into chain before, after specific Filter, replace one. Application configures HTTP BAsic Authentication, so there is BasicAuthenticationFilter configured by Spring. Add the ApiKeyFilter before the BasicAuthenticationFilter. Use addFilterBefore() method of the HttpSecurity configuration.

  4. Start the application and verify, if Filter works as expected. The HTTP 401 response should be returned, if there is invalid APi Key provided in the request.