从浏览器进行API调用是有效的,但不是来自前端应用

时间:2016-05-20 22:20:32

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

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

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

enter image description here

当我从浏览器调用此API时,它可以正常工作:

enter image description here

        // 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错误:

enter image description here

    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)]

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

2 个答案:

答案 0 :(得分:0)

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

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

另请参阅:angular2 xhrfields withcredentials true

答案 1 :(得分:0)

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

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

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