简体   繁体   中英

Angular 4 Front End hosted on Azure CORS Issue

I'm building a web app with Angular 4 that's trying to POST to the VSTS Rest API. I obviously don't own the service and I'm trying to run in live in Azure and NOT locally (I understand that I can disable CORS in chrome for local testing).

Failed to load 
https://app.vssps.visualstudio.com/oauth2/tokenRemovedtoStackOverflow 
Response to preflight request doesn't pass access control check: No 'Access-
Control-Allow-Origin' header is present on the requested resource. Origin 
'https://blah.azurewebsites.net' is therefore not allowed access. The 
response had HTTP status code 400.

Call is basically:

private _appID = blah;
private _tokenRequest = 'client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_assertion={0}&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion={1}&redirect_uri={2}';
  private _returnURI = 'https://blah.azurewebsites.net/';
  private headers = new Headers(
    {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers': 'Content-type',
      'Content-Type': 'application/x-www-form-urlencoded',
    });

  constructor(private http: Http) { }

  getAccessToken(code: string): Observable<IToken> {
    const _url = 'https://app.vssps.visualstudio.com/oauth2/' + code;
        const body = 'client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_assertion=' +
      this._appID +
      '&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=' +
      code + '&redirect_uri=' +
      this._returnURI;
    const options = new RequestOptions();
    options.headers = this.headers;

      return this.http
        .post(_url, body, options)
        .map((response: Response) => <IToken[]> response.json())
        .do(data => console.log('All: ' +  JSON.stringify(data)))
        .catch(this.handleError);

Currently I have no server/api(AKA the only thing in my source is angular) and it's just running on whatever server Azure web app provides.

Is my only choice to get around the CORS adding a nodejs server to host this in azure?

Access-Control-Allow-Origin and Access-Control-Allow-Headers are response headers. They have no place on your request.

Adding custom headers is one of the triggers of the preflight OPTIONS request that is generating the 400 error.

Removing them should cause the request to be a simple request and might be allowed by the service.

Failing that: Yes, you need to change the host so that it grants you permission.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM