Pavel
Pavel

Reputation: 2101

Specifying CORS headers for withCredentials: true

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);
    }
}

Upvotes: 0

Views: 2949

Answers (2)

tom
tom

Reputation: 2745

You also need to add the Access-Control-Allow-Origin header.

response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");

If you are doing cross origin calls with credentials you will need to add the explicit host and not *. Otherwise your call will be blocked by the browser.

-

If you are using spring you could also use their crossorigin tag: https://spring.io/guides/gs/rest-service-cors/

Upvotes: 0

Sarjerao Ghadage
Sarjerao Ghadage

Reputation: 1544

create constant service component and inject it in service method call ex:

service.ts

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
  withCredentials: true,
};



demoServiceMethod(requestparameter): Observable<PayloadResponse<any>> {
    return this.http.post<PayloadResponse<any>>(environment.baseurl +
      'v1/test/api', requestparameter, httpOptions)
      .pipe(catchError(this.apiErrorService.handleError<PayloadResponse<any>>('operation name  ')));
  }

Upvotes: 1

Related Questions