Angular 2 API call with basic security authorization

I am trying to call an ASP Web API embedded HTTP method from an Angular 2 client. And I am getting this error:

OPTIONS http: // endpoint / api / Get? Key = something 401 (unauthorized)

XMLHttpRequest cannot load http: // endpoint / api / Get? Key = something . Preflight Request Response Fails Access Control Check: None The Access-Control-Allow-Origin header is present on the requested resource. Origin ' http: // localhost: 4200 ' is therefore not allowed access. The response was HTTP 401 status code.

Here is my implementation that works well when I disable 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());
    }   
}

      

+3


source to share


1 answer


This looks more like a CORS bug than an angular / typescript bug. You are trying to navigate from "localhost" to "endpoint". You must configure the endpoint service to allow requests from this domain.



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

+1


source







All Articles