0

I have backend app written in java ee and jersey. When I posting data to my rest endpoint, using JavaScript Fetch API I see that the filter is fired twice. Once it haven't authorization header, second it have. When I try open my site from web browser then this filter is called only once. Why this happened. Maybe it's because of CORS?

below my logs from single post both printed from the same filter.

 http://localhost:8080/BlogRest/controller/endpoint/|#]
  Key=host, value=localhost:8080|#]
  Key=origin, value=http://localhost:3000|#]
  Key=access-control-request-method, value=POST|#]
  Key=content-length, value=0|#]
  Key=access-control-request-headers, value=authorization,content-type|#]
  Key=connection, value=keep-alive|#]
  Key=accept, value=*/*|#]
  Key=user-agent, value=user agent data|#]
  Key=referer, value=http://localhost:3000/|#]
  Key=accept-language, value=pl-pl|#]
  Key=accept-encoding, value=gzip, deflate|#]
  

second call

  http://localhost:8080/BlogRest/controller/endpoint/|#]
  Key=host, value=localhost:8080|#]
  Key=origin, value=http://localhost:3000|#]
  Key=content-type, value=application/json|#]
  Key=accept-language, value=pl-pl|#]
  Key=accept-encoding, value=gzip, deflate|#]
  Key=connection, value=keep-alive|#]
  Key=accept, value=*/*|#]
  Key=user-agent, value=user agent data|#]
  Key=authorization, value=Bearer token|#]
  Key=referer, value=http://localhost:3000/origin|#]
  Key=content-length, value=15|#]
Bogus
  • 283
  • 1
  • 2
  • 13

1 Answers1

0

There are two requests because of CORS. One request method is OPTIONS, and when it is preformed then starts expected POST request. OPTIONS request doesn't call the endpoint, it just get te server configuration. So I filtered in my Java filter request by method using HttpServletRequest getMethod().

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest requ = (HttpServletRequest) request;

        if (requ.getMethod().toLowerCase().equals(HttpMethod.OPTIONS)) {
            chain.doFilter(request, response);
            return;
        }

        //do something on not options method.            

        chain.doFilter(request, response);

    }
Bogus
  • 283
  • 1
  • 2
  • 13