错误:从Angular6到ASP.NET Core 2.1实施AntiCrossSiteForgery POST请求

时间:2018-08-23 11:22:35

标签: c# angular asp.net-core asp.net-core-2.1

美好的一天

在我的ASP.NET Core Web API 2.1上发送发布请求时,我收到400 bad request

enter image description here

enter image description here

我有2个项目。首先是Angular6作为我的休息客户端,其次是我的ASP.NET Core 2.1 Web API作为我的休息服务器。

为了向您展示我所做的事情,这是我的角度spa代码:

我有一个方法可以在我的api上获取令牌。它返回一个字符串

saveAntiForgeryToken(){
    this.getToken().subscribe((response: any) => {
      localStorage.setItem('antiforgerytoken', response.token);
    }, error => {
    console.log(`Something went wrong ${error}`);
    });
}

在我的邮政服务中,我有以下代码:

submitInfo(info: any){
     this.http.post(`${environment.apiUrl}Info`, info, {
        headers: {
            'X-XSRF-TOKEN': localStorage.getItem('antiforgerytoken')
        }
    });
}

在使用ASP.NET Core Web API时,我对Startup.cs所做的更改很少

public void ConfigureServices(IServiceCollection services)
{
    services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
    ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IAntiforgery antiforgery)
{
    ... 
    app.Use(next => context =>
    {
        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("X-XSRF-TOKEN", tokens.RequestToken, new CookieOptions { HttpOnly = false });
         }
         return next(context);
    });
}

在我的控制器上

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Info info) { ... }

最后,负责获取防伪令牌的api代码方法

[HttpGet]
public async Task<IActionResult> RetrieveToken()
{
    var retrievedToken = await Task.FromResult(
         new {
                token = antiForgery.GetAndStoreTokens(HttpContext).RequestToken
    });
    return Ok(retrievedToken);
}

请帮助。我坚持了好几天。 :(

0 个答案:

没有答案