【问题标题】:Angular 2 calling API with Basic Security Authorization具有基本安全授权的 Angular 2 调用 API
【发布时间】:2017-10-22 03:45:11
【问题描述】:

我正在尝试从 Angular 2 客户端调用使用 ASP Web API 实现的 HTTP 方法。 我收到了这个错误:

选项http://endpoint/api/Get?key=something 401(未经授权)

XMLHttpRequest 无法加载 http://endpoint/api/Get?key=something。回应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:4200” 使用权。响应的 HTTP 状态代码为 401。

这是我的实现,当我在 IIS 服务器上禁用基本身份验证时效果很好:

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

【问题讨论】:

  • 也许你最后解决了?同样的问题

标签: typescript asp.net-web-api2 angular2-services angular2-http


【解决方案1】:

这看起来更像是 CORS 错误,而不是 angular/typescript 错误。您正在尝试从“localhost”跨越到“endpoint”。您必须配置端点服务以允许来自该域的请求。

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

【讨论】:

  • 已经在 WebApiConfig 中以这种方式完成: var cors = new EnableCorsAttribute( origins: "", headers: "", methods: "*"); config.EnableCors(cors);正如我提到的,当我在 IIS 上禁用基本身份验证时,它运行良好。
猜你喜欢
  • 2015-12-10
  • 2013-01-22
  • 1970-01-01
  • 2014-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-11
相关资源
最近更新 更多