我有两个独立的项目:前端应用程序(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)]
我绝对是这个角色的成员,当我从前端应用程序拨打电话时,它就像我从浏览器拨打电话时那样无法识别。
答案 0 :(得分:0)
您的项目是否部署到不同的域? (http://localhost:8462
和http://localhost
被视为不同的域名)
如果是,则必须将withCredentials: true
添加到Angular2 HTTP后端。
答案 1 :(得分:0)
将此添加到前端应用: https://github.com/angular/http/issues/65#issuecomment-181560171
将其添加到Startup.cs中的后端应用程序:
app.UseCors(builder =>
builder.AllowAnyOrigin()
.AllowCredentials()
.AllowAnyHeader()
.AllowAnyMethod()
);