View Javadoc
1   package net.sumaris.server.http.filter;
2   
3   /*-
4    * #%L
5    * SUMARiS:: Server
6    * %%
7    * Copyright (C) 2018 SUMARiS Consortium
8    * %%
9    * This program is free software: you can redistribute it and/or modify
10   * it under the terms of the GNU General Public License as
11   * published by the Free Software Foundation, either version 3 of the
12   * License, or (at your option) any later version.
13   * 
14   * This program is distributed in the hope that it will be useful,
15   * but WITHOUT ANY WARRANTY; without even the implied warranty of
16   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   * GNU General Public License for more details.
18   * 
19   * You should have received a copy of the GNU General Public
20   * License along with this program.  If not, see
21   * <http://www.gnu.org/licenses/gpl-3.0.html>.
22   * #L%
23   */
24  
25  import org.springframework.core.annotation.Order;
26  import org.springframework.stereotype.Component;
27  
28  import javax.servlet.*;
29  import javax.servlet.http.HttpServletRequest;
30  import javax.servlet.http.HttpServletResponse;
31  import java.io.IOException;
32  
33  @Component
34  @Order(0)
35  public class CORSFilter implements Filter {
36  
37      @Override
38      public void init(FilterConfig filterConfig) throws ServletException {
39  
40      }
41  
42      @Override
43      public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
44          HttpServletRequest request = (HttpServletRequest) req;
45          HttpServletResponse response = (HttpServletResponse) res;
46  
47          response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
48          response.setHeader("Access-Control-Allow-Credentials", "true");
49          response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT, OPTIONS");
50          response.setHeader("Access-Control-Max-Age", "3600");
51          response.setHeader("Access-Control-Allow-Headers", "accept, access-control-allow-origin, authorization, content-type");
52  
53          if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
54              response.setStatus(HttpServletResponse.SC_OK);
55          } else {
56              chain.doFilter(req, res);
57          }
58      }
59  
60      @Override
61      public void destroy() {
62  
63      }
64  }