View Javadoc
1   package com;
2   
3   /*
4    * #%L
5    * Gateway
6    * %%
7    * Copyright (C) 2015 Powered by Sergey
8    * %%
9    * Licensed under the Apache License, Version 2.0 (the "License");
10   * you may not use this file except in compliance with the License.
11   * You may obtain a copy of the License at
12   * 
13   *      http://www.apache.org/licenses/LICENSE-2.0
14   * 
15   * Unless required by applicable law or agreed to in writing, software
16   * distributed under the License is distributed on an "AS IS" BASIS,
17   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18   * See the License for the specific language governing permissions and
19   * limitations under the License.
20   * #L%
21   */
22  
23  import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper;
24  import org.springframework.stereotype.Component;
25  
26  import javax.servlet.*;
27  import javax.servlet.http.HttpServletResponse;
28  import java.io.IOException;
29  
30  
31  @Component
32  public class CORSFilter implements Filter {
33  
34      public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
35          HttpServletResponse response = (HttpServletResponse) res;
36  
37          if(req instanceof SecurityContextHolderAwareRequestWrapper){
38              if(((SecurityContextHolderAwareRequestWrapper) req).getHeaders("Origin") != null && ((SecurityContextHolderAwareRequestWrapper) req).getHeaders("Origin").hasMoreElements()){
39                  String origin = ((SecurityContextHolderAwareRequestWrapper) req).getHeaders("Origin").nextElement().toString();
40  
41                  if(origin.equals("http://localhost:63769") || origin.equals("http://localhost:1000") || origin.equals("http://localhost:1001")){
42                      response.setHeader("Access-Control-Allow-Origin", origin);
43                  }
44              }
45          }
46  
47          response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
48          response.setHeader("Access-Control-Max-Age", "3600");
49          response.setHeader("Access-Control-Allow-Credentials", "true");
50          response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
51          chain.doFilter(req, res);
52      }
53  
54      public void init(FilterConfig filterConfig) {}
55  
56      public void destroy() {}
57  
58  }