我正在开发一个样本SPA,使用ASP.NET MVC作为后端,Angular 2作为前端 .
我按照以下步骤来防止我的应用程序中的跨站点请求伪造攻击
- 由于ASP.NET MVC发送一个名为“__RequestVerificationToken”的cookie,并且在HTTP请求中需要一个名为“__RequestVerificationToken”的头来阻止CSRF,我在我的angular模块中添加了以下代码
{provide: XSRFStrategy, useFactory: xsrfFactory}
其中xsrfFactory低于函数
export function xsrfFactory() {
return new CookieXSRFStrategy('__RequestVerificationToken', '__RequestVerificationToken');
}
- 以下是具有“[ValidateAntiForgeryToken]”属性的控制器操作代码,使用Angular 2的Http服务将对其进行AJAX调用 .
[CustomAuth]
[ValidateAntiForgeryToken]
public ActionResult GetAuthors()
{
List<BookStoreAdmin.ViewModels.Author> authors = BookStoreAdmin.BAL.Author.GetAuthors();
BookStoreAdmin.ViewModels.Response<List<BookStoreAdmin.ViewModels.Author>> response = new Response<List<ViewModels.Author>>();
response.success = true;
response.errorMessage = null;
response.data = authors;
return Json(response, JsonRequestBehavior.AllowGet);
}
- 以下是进行AJAX调用的代码 .
loadAuthors(): Observable<AuthorModel[]> {
return this.http.get('http://localhost:57599/author/GetAuthors')
.map((data) => data.json());
}
当我的应用程序使用Http角度服务进行AJAX调用时,我希望它有名称为“__RequestVerificationToken”的请求标头,但是这个标头丢失了,任何想法可能是什么原因?
如果需要提供更多信息,请告诉我?
2 回答
我无法看到你是否在angular2 http调用中传递了一个 Headers .
您可以使用RequestOptions API,它允许您添加 header . 在您发出请求后添加标头后,
ValidateAntiForgeryToken
应该能够接收已发送的标头 .在这里阅读更多 RequestOptions :
https://angular.io/docs/ts/latest/api/http/index/RequestOptions-class.html
迟到的答案可能对某人有用 .
我认为标头没有设置,因为这是一个GET请求 . 虽然这是Angular 2,但角度4 security docs可能与此相关,因为它们表明了这一点
为了在his answer中明确将此标头包含为@micronyks状态,您可以使用RequestOptions API . 这是一个代码示例