gsmida
gsmida

Reputation: 357

Angular 2 calling API with Basic Security Authorization

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());
    }   
}

Upvotes: 4

Views: 2415

Answers (1)

Josh Knack
Josh Knack

Reputation: 405

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

Upvotes: 1

Related Questions