Angular: A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true

I know there are a lot of questions concerning CORS already but they don’t seem to answer my question.

So I have a client app written in Angular which will be used to create a mobile app (with Apache Cordova). The html files and JavaScript files will be loaded from the mobile device.
When I simulate that and I send requests to the REST API server I first got
“No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:82‘ is therefore not allowed access”.
So I added header(“Access-Control-Allow-Origin: *”); in my php REST API Server. I cannot specify a specific domain as the requests will come from the mobile devices.

Now I got to “A wildcard ‘*’ cannot be used in the ‘Access-Control-Allow-Origin’ header when the credentials flag is true.”

I finally found a solution but I’m not sure it is safe to keep it like this.

In my php REST API Server I added this:

if (isset($_SERVER['HTTP_ORIGIN'])) {
  header("Access-Control-Allow-Credentials: true");
  header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
  header("Access-Control-Allow-Headers: *, X-Requested-With, Content-Type");
  header("Access-Control-Allow-Methods: GET, POST, DELETE, PUT");
}

Please advise on this way of working. If it is not secure or no good at all, can you please tell me how to solve this issue?

Thanks a lot!

Why does Angular2 require CORS when loading main.js from foreign server?

I get this error:

XMLHttpRequest cannot load http://otherwebsite.com/myapp/app/main.js.
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://otherwebsite.com' is therefore not allowed access.

when referencing a main.js file in Angular2:

System.import('http://otherwebsite.com/myapp/app/main')

But no other .js files require CORS pulled from the other site.

I know how to add CORS support for Web API 2 for methods but this is not a method. I know how to add CORS support for Apache folders in .htaccess files. And with a little digging I found how to add IIS 7 CORS folder support that made this error go away.

Buy why would Angular2 need CORS for my main.js when all the other .js files loaded without CORS issues?

Angular 2 – No 'Access-Control-Allow-Origin' header is present on the requested resource

When trying to make API Calls from my Angular 2 App to my API, I get the following error:

XMLHttpRequest cannot load http://localhost/myAPI/public/api/v1/auth/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 422.

I’ve been checking every single question on the web and anything releated to CORS, nothing solved my problem!

My Laravel API running on port 80. (localhost)

My angular 2 app running on port 3000. (localhost:3000)

  • I’ve been trying to enable cors in Laravel side with Cors middleware
  • The API calls are working using chrome web security off. The first answer here solves the problem, But I really want to stop using the CMD and unsecured chrome version everytime im testing my app.
  • Using chrome extension POSTMAN API calls to my API are working.

So.. What’s wrong? Why my Angular 2 app cant get records from my API?

Setting Access-Control-Allow-Origin header in Angular2 development mode

I am making HTTP requests to an external server which of CORS don’t make it through.

In production I will set the Access-Control-Allow-Origin header in nginx.
Is there a way to also set the header in the “built-in” Angular’s development server so that I don’t need to run any proxy on my laptop?

Preflight CORS requests with Basic Authentication in Angular 2

I am building an Angular 2 app that needs to send a CORS (Cross-origin resource sharing) POST request with Basic Authentication (https://en.wikipedia.org/wiki/Basic_access_authentication) to the server.

I am nicely setting the Authorization header for the POST request itself but as it is CORS, the browser first automatically sends the preflight OPTIONS request.
Unfortunately the server is misconfigured (Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?) and requires the Basic Auth also in the preflight. It is a 3rd party server, I can’t change it.

Is there a way to overcome it (e.g. add the Authorizion header to preflights, disable preflights, …)?

Setting JSON request header in Angular2 HTTP POST

I’m having a problem setting a content-type of application/json header on my post request.

    saveUpdates(alltabs: AllTabs): Observable<Response> {
            let api = this.host + this.routes.save;
            let headers = new Headers();
            headers.append('Content-Type', 'application/json');

            return this._http.post(api, JSON.stringify(alltabs), { headers: headers })
            .map((response: Response) => <Response>response.json())
            .do(data => console.log("saveUpdates(): " + data))
            .catch(this.handleError);
    }

Request Headers:

OPTIONS /api/productsave HTTP/1.1
Host: wbtest:92
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: POST
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://localhost:3000/product/60000010080
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

Response Headers:

HTTP/1.1 405 Method Not Allowed
Cache-Control: no-cache
Pragma: no-cache
Allow: POST
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Date: Tue, 14 Jun 2016 15:16:15 GMT
Content-Length: 76

As you can see, my request has two unexpected headers added “Access-Control-Request-Headers” and “Access-Control-Request-Method”. This seems to suggest an issue with CORS (Cross-Origin Resource Sharing). However, the web.conf file on the API server has been working and the response headers states “Access-Control-Allow-Origin: *”.

Any idea what could be wrong?

UPDATE:

The above code is correct – the problem is with the Sever code not being configured to handle preflight requests. In my case, the .NET Web API 2 application was not configured to allow CORS.

I can't expose my response header using CORS

I am currently using angular2 to retrieve a JWT token from my API. The API is generating and responding with the token perfectly, it stores the token in the response header.

I can clearly see that the token exist using postman or my chrome network response header tab but my angular2 can’t. I currently have this code in my angular 2 app to help expose it but I still can’t see it.

'Access-Control-Allow-Origin', '*'
'Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, DELETE';
'Access-Control-Allow-Headers', 'token'
'Access-Control-Allow-Credentials', 'true'
'Access-Control-Expose-Headers', 'token'

Set headers on get request angular 2

I try to set an Authorization header to a GET request to authenticate users to a rest API. I’m using Angular 2 RC1. (I’am a total beginner).

getTest(){
    let authToken = localStorage.getItem('auth_token');
    let headers = new Headers({ 'Content-Type': 'application/json' });
    headers.append('Authorization', `Bearer ${authToken}`);

    let options = new RequestOptions({ headers: headers });
    return this._http
      .get(this._url,options)
      .map(res => console.log(res));
  }

I allow CORS in my backend.

header("Access-Control-Allow-Origin: *");
header("Access-Control-Request-Headers: Content-Type, Authorization");

My console :

OPTIONS api/userProfile/

XMLHttpRequest cannot load /userProfile/. Response for preflight has
invalid HTTP status code 406

My request headers

Any idea ?

Angular2 Yelp API CORS error

While implementing the V3 API I face the following CORS problem with my Ionic2/Angular2 application:

XMLHttpRequest cannot load https://api.yelp.com/v3/businesses/search. 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:8100‘ is therefore not allowed access. The response had HTTP status code 404.

While using the V2 of the API, I was “bypassing” the CORS problem using http.jsonp whish isn’t applicable anymore, because the authorization bearer should be added in the header of the GET request (as far as I understood, a Jsonp header can’t be modified).

That’s why I tried

private queryYelp(yelpOAuth:YelpCommunication.YelpOAuthSignature, nextTo:AddressLocation.Location):Promise<{}> {

    let params:URLSearchParams = new URLSearchParams();

    params.set('limit', '' + Resources.Constants.Default.YELP.LIMIT);
    params.set('latitude', '' + nextTo.coordinates[0]);
    params.set('longitude', '' + nextTo.coordinates[1]);
    params.set('radius', '' + Resources.Constants.Default.YELP.RADIUS);
    params.set('sort_by', Resources.Constants.Default.YELP.SORT.BEST_MATCHED);

    let headers:Headers = new Headers();
    headers.append('Authorization', 'Bearer ' + yelpOAuth.access_token);
    let options:RequestOptions = new RequestOptions({
        headers: headers,
        search: params,
        withCredentials: true
    });

    return new Promise((resolve, reject) => {
        this.http.get(Resources.Constants.Default.YELP.URL, options)
            .map(res => res.json())
            .subscribe((businesses:Yelp.YelpBusiness[]) => {
                resolve(businesses);
            }, (errorResponse:Response) => {
                reject(errorResponse);
            });
    });
}

or

private queryYelp(yelpOAuth:YelpCommunication.YelpOAuthSignature, nextTo:AddressLocation.Location):Promise<{}> {
    return new Promise((resolve, reject) => {
        let xhr:XMLHttpRequest = new XMLHttpRequest();

        let formData:FormData = new FormData();
        formData.append('limit', '' + Resources.Constants.Default.YELP.LIMIT);
        formData.append('latitude', '' + nextTo.coordinates[0]);
        formData.append('longitude', '' + nextTo.coordinates[1]);
        formData.append('radius', '' + Resources.Constants.Default.YELP.RADIUS);
        formData.append('sort_by', Resources.Constants.Default.YELP.SORT.BEST_MATCHED);

        xhr.onload = () => {
            console.log("status " + xhr.status);
            if (xhr.readyState === XMLHttpRequest.DONE && xhr.status == 201) {
                let businesses:Yelp.YelpBusiness[] = JSON.parse(xhr.responseText);
                resolve(businesses);
            } else {
                reject();
            }
        };

        xhr.onerror = () => {
            alert('Woops, there was an error making the request.');
        };

        xhr.open("GET", Resources.Constants.Default.YELP.URL, true);
        xhr.setRequestHeader("Authorization", 'Bearer ' + yelpOAuth.access_token);
        xhr.send(formData);
    });
}

and both solution weren’t successful aka both solution leaded to the CORS error listed above.

Did I miss something or how could I query the Yelp API v3 from Ionic2 / Angular2?

Thx
Best regards

P.S.: Note that my OAuth access_token isn’t exposed. The authentication is generated by my backend.

UPDATE

After @Thierry Templier answer I found a solution which works for Ionic2.

When debugging in the browser, I query the Yelp API V3 using a proxy. Therefor I add in ionic.config.json file

 "proxies": [{
    "path": "/yelp/v3/businesses",
    "proxyUrl": "https://api.yelp.com/v3/businesses"
 }]

and do the query like following

this.http.get('http://localhost:8100/yelp/v3/businesses/' + 'search', ...

note that following would also work

this.http.get('/yelp/v3/businesses' + 'search', ...

When running in iOS and Android, the proxy should not be use aka not gonna work. Therefor I do the query like following in my service

this.http.get('https://api.yelp.com/v3/businesses/search, ...

Of course, to have something handy, I write a gulp task which allow me to switch between environments.

But, this solution is only applicable for Ionic2. If I would have to implement it in Angular2 in a website, I would need I guess a proxy too, not sure about it. Therefor I opened a copy of that task in the issues list of the Yelp API V3

https://github.com/Yelp/yelp-api-v3/issues/21