4

I'm trying to call an HTTP method implmented with ASP Web API from an Angular 2 client. And I'm getting this error:

OPTIONS http://endpoint/api/Get?key=something 401 (Unauthorized)

XMLHttpRequest cannot load http://endpoint/api/Get?key=something. 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 401.

Here is my implementation, which works well when I disable the basic authentication on the IIS Server:

import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map'
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Entity } from "app/view-models/entity";

@Injectable()
export class HttpService {
    headers;
    options;
    constructor(private _http: Http) {
        this.headers = new Headers();
        this.headers.append('Authorization', 'Basic ' + btoa('username:password'));
        this.headers.append("Access-Control-Allow-Credentials", "true");
        this.headers.append('Content-Type', 'application/x-www-form-urlencoded');
        this.options = new RequestOptions();
        this.options = new RequestOptions({ headers: new Headers(this.headers) });
    }

    public Get = (): Observable<Entity> => {
        var params = '?key=something';
        return this._http.get(environment.apiBaseUrl + environment.getSettings + params
            , this.options)
            .map(response => <Entity>response.json());
    }   
}
1
  • Maybe you solved in The end? Same problem here Commented Jun 28, 2017 at 23:07

1 Answer 1

1

This looks more like a CORS error than an angular/typescript error. You're trying to cross from "localhost" to "endpoint". You have to configure your endpoint service to allow requests from this domain.

https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Sign up to request clarification or add additional context in comments.

1 Comment

It is already done in the WebApiConfig this way: var cors = new EnableCorsAttribute( origins: "", headers: "", methods: "*"); config.EnableCors(cors); And as I mentionned when when I disable the basic authentication on the IIS it works well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.