【问题标题】:Making an API call from browser works, but not from front end app从浏览器进行 API 调用有效,但不能从前端应用程序调用
【发布时间】:2016-05-20 22:20:32
【问题描述】:

我有两个独立的项目:一个前端应用程序(Angular 2,使用 Visual Studio Code)和一个后端应用程序(ASP.NET Core,使用 Visual Studio 2015)。对于后端应用程序,当我执行文件 > 新建项目时,我选择了“Windows 身份验证”。

在属性下,我选中了这些框:

当我从我的浏览器调用这个 API 时,它工作得很好:

        // GET: api/card
        [HttpGet]
        [Authorize(Roles = ActiveDirectory.User)]
        public Card[] Get()
        {
            var cards = _cardData.GetAll().ToList();

            var result = cards
                            .OrderByDescending(x => x.LastChanged);

            return result.ToArray();
        }

但是当我从前端应用程序拨打电话时,我收到 401 错误:

    private _cardUrl = 'http://localhost:8462/api/card';

    getCards(): Observable<Card[]> {
        return this._http.get(this._cardUrl)
            .map((response: Response) => <Card[]>response.json())
            .catch(this.handleError);
    }

我应该指出,当我删除这一行时,它工作得很好:[Authorize(Roles = ActiveDirectory.User)]

我绝对是这个角色的一员,只是当我从前端应用程序拨打电话时它无法识别它,就像我从浏览器拨打电话时一样。

【问题讨论】:

    标签: asp.net-web-api angular asp.net-core asp.net-core-mvc windows-authentication


    【解决方案1】:

    您的项目是否部署到不同的域? (http://localhost:8462http://localhost 被认为是不同的域)

    如果是,您必须将 withCredentials: true 添加到您的 Angular2 HTTP 后端。

    另请参阅:angular2 xhrfields withcredentials true

    【讨论】:

    • 是的,后端应用在localhost:8462,前端应用在localhost:3000
    • 那么你必须添加withCredentials否则浏览器不会通过XHR发送任何凭据信息。
    【解决方案2】:

    将此添加到前端应用程序: https://github.com/angular/http/issues/65#issuecomment-181560171

    将此添加到 Startup.cs 中的后端应用程序:

    app.UseCors(builder =>
                builder.AllowAnyOrigin()
                        .AllowCredentials()
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                );
    

    【讨论】:

      猜你喜欢
      • 2016-07-30
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 2017-11-10
      • 2014-03-08
      • 1970-01-01
      相关资源
      最近更新 更多