1

我在Angular 2中使用独立的前端项目而不使用MVC,而后端项目是Web Api(Asp.Net Core)都托管在不同的域中。我实现了AntiForgery令牌功能,但它不起作用。使用Aps.Net核心在Angular 2和Web Api中实现AntiForgery令牌实现我使用Aps.Net核心

前端项目(UI) -​​

后端项目(网页API) - http://localhost:4823/

我能接受,并在每个请求发送XSRF-Token Cookie,但API为400 Bad Request错误。 我跟着这个链路 Angular2 ASP.NET Core AntiForgeryToken

Startup.cs -

public void ConfigureServices(IServiceCollection services) 
{ 
    services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN"); 
    services.AddCors(options => 
    { 
     options.AddPolicy("AllowAllCorsPolicy", 
     builder => builder.AllowAnyOrigin() 
        .AllowAnyMethod() 
        .AllowAnyHeader() 
        .AllowCredentials()); 
    }); 
} 


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider, IAntiforgery antiforgery) 
{ 
    app.Use(async (context, next) => 
     { 
     if (context.Request.Path == "/") 
      { 
      //send the request token as a JavaScript-readable cookie, and Angular will use it by default 
      var tokens = antiforgery.GetAndStoreTokens(context); 
      context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions { HttpOnly = false }); 
      } 
     } 
} 

控制器代码 -

​​

角代码 -

let options = new RequestOptions({ headers: headers, withCredentials:true }); 
this._http.post(this.aoiUrl, bodydata, options) 
     .map((res: Response) => { 
      let data = res.json(); 
      return data; 
}) 

enter image description here

回答

0

Cookie不能跨越跨域共享。所以即使您的web api项目将XSRF-TOKEN附加到其上下文响应中,它也可用于托管在单独域中的前端应用程序,而不是而不是。我看到一些变通办法,通过配置AddAntiforgery()服务的选项,在两个应用程序中使用固定的Cookie名称