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.
On UI side I call server with next TS code:
@Injectable()
export class CoreApi {
private baseUrl = 'http://localhost:8080/rest/';
constructor(public http: HttpClient) {
}
public get(url: string = ''): Observable<any> {
return this.http.get(this.getUrl(url), { withCredentials: true });
}
public post(url: string, data: any = {}): Observable < any > {
return this.http.post(this.getUrl(url), data, { withCredentials: true });
}
private getUrl(url: string = ''): string {
return this.baseUrl + url;
}
}
I need withCredentials: true
for sending cookie
otherwise Spring Security not recognize the user without the session id. But on the server, I put response.setHeader("Access-Control-Allow-Origin", "*")
for possibility work with two different servers for the UI and the backend.
And I in a vicious circle: if I delete Access-Control-Allow-Origin - *
I get :
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
If I delete withCredentials: true
Spring Security doesn't work correctly without session id. And all request after authentification - UNAUTHORIZED
without the cookie.
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!
May be filter something like this:
@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);
}
}