title: Specifying CORS headers for withCredentials: true
body: <p>I need Specifying CORS headers cause I need to send cookie key in each request. I have a backend with Java Spring Boot and UI with Angular 5 on different servers.</p>
  
  <p>On UI side I call server with next TS code:</p>
  
  <pre><code>@Injectable()
  export class CoreApi {
    private baseUrl = 'http://localhost:8080/rest/';
  
    constructor(public http: HttpClient) {
    }
  
    public get(url: string = ''): Observable&lt;any&gt; {
      return this.http.get(this.getUrl(url), { withCredentials: true });
    }
  
    public post(url: string, data: any = {}): Observable &lt; any &gt; {
      return this.http.post(this.getUrl(url), data, { withCredentials: true });
    }
  
    private getUrl(url: string = ''): string {
      return this.baseUrl + url;
    }
  }
  </code></pre>
  
  <p>I need <code>withCredentials: true</code> for sending <code>cookie</code> otherwise Spring Security not recognize the user without the session id. But on the server, I put <code>response.setHeader("Access-Control-Allow-Origin", "*")</code> for possibility work with two different servers for the UI and the backend.</p>
  
  <p>And I in a vicious circle: if I delete <code>Access-Control-Allow-Origin - *</code> I get :</p>
  
  <pre><code>No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
  </code></pre>
  
  <p>If I delete <code>withCredentials: true</code> Spring Security doesn't work correctly without session id. And all request after authentification - <code>UNAUTHORIZED</code> without the cookie.</p>
  
  <p>I think need implement an origin whitelist and respond to CORS requests with a valid origin whenever credentials are involved. But how do this?
  If you know about this anything please let me know. Thank You!</p>
  
  <p>May be filter something like this:</p>
  
  <pre><code>@WebFilter(urlPatterns = {"/*" })
  public class CorsRestFilter implements Filter {
      public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
          ...somehow sfecifying Access-Control-Allow-Origin...
          response.setHeader("Access-Control-Allow-Methods", "POST, GET");
          chain.doFilter(req, res);
      }
  }
  </code></pre>