0

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);
    }
}
Pavel
  • 1,436
  • 3
  • 19
  • 39
  • When you say CROS, do you mean CORS? – Andreas May 09 '18 at 00:32
  • @Andreas yes this is my mistake. Thank you for comment. I fix it. – Pavel May 09 '18 at 00:40
  • @user3624390 Spring Security reject my request from ((( `Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403.` Maybe I add this expression in wrong place... Maybe exist the place for global configuration this. – Pavel May 09 '18 at 01:16
  • 1
    Here is a good explanation of how to setup the request headers and cors filter: https://stackoverflow.com/questions/8685678/cors-how-do-preflight-an-httprequest?rq=1 – user3624390 May 09 '18 at 01:21

2 Answers2

1

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  ')));
  }
Sarjerao Ghadage
  • 952
  • 8
  • 23
  • how is this related to the question. The angular part seems to be working correctly. The question is more about java side of things. – tom May 09 '18 at 07:20
0

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/

tom
  • 2,685
  • 19
  • 35