如何在提取中使用AntiForgeryToken?

时间:2018-11-25 15:33:00

标签: c# asp.net-core-mvc fetch

我不确定如何在我的Fetch调用中使用AntiForgeryToken。对于AJAX示例,我在这里找到: include antiforgerytoken in ajax post ASP.NET MVC

我可以用相同的方式来实现它吗?我找不到任何例子。任何帮助将不胜感激。

我的控制器的方法如下:

[Route("comments/new")]
        public ActionResult AddComment(Survey survey)
        {
            survey.Time = DateTime.Now;
            _context.Surveys.Add(survey);
            _context.SaveChanges();
            return Content("Added");
        }

和前端:

const queryParams = `Name=${this.state.surveyState.name}&Change=${this.state.surveyState.change}&Opinion=${this.state.surveyState.opinion}`;
                    fetch(`/comments/new?${queryParams}`)
                        .then(res => res.json())
                        .then(res => {
                            console.log(res);
                        })
                        .catch(error => {
                            console.error(error);
                        });

1 个答案:

答案 0 :(得分:0)

我的最终解决方案。 在Startup.cs中需要添加:

//config found in some tutorial, sometimes you can find with z X-XSRF-TOKEN, didnt test it
public void ConfigureServices(IServiceCollection services)
{
(...)
services.AddAntiforgery(x => x.HeaderName = "X-CSRF-TOKEN");
services.AddMvc();
}
(...)
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
                    var tokens = antiforgery.GetAndStoreTokens(context);
                    context.Response.Cookies.Append("CSRF-TOKEN", tokens.RequestToken, new CookieOptions { HttpOnly = false });
                }
                return next(context);
            });
            app.UseAuthentication();
            app.UseStaticFiles(); //new configs supposed to be before this line

我在POST中的SurveyController.cs

[HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult AddComment(Survey survey)
        {
            if (survey == null)
            {
                return BadRequest();
            }
            survey.Time = DateTime.Now;
            _context.Surveys.Add(survey);
            _context.SaveChanges();

            return Ok();
        }

JS文件中,我有Dialog.js,需要创建获取Cookie的函数:

//it is similar like here: https://www.w3schools.com/js/js_cookies.asp
function getCookie(name) {
    if (!document.cookie) {
        return null;
    }
    const csrfCookies = document.cookie.split(';')
        .map(c => c.trim())
        .filter(c => c.startsWith(name + '='));
    if (csrfCookies.length === 0) {
        return null;
    }
    return decodeURIComponent(csrfCookies[0].split('=')[1]);
}

下一步,当触发Fetch时:

var csrfToken = getCookie("CSRF-TOKEN");
                    //recommended way in documentation
                    var url = new URL("http://localhost:58256/Survey/AddComment"),
                        params = { Name: this.state.surveyState.name, Change: this.state.surveyState.change, Opinion: this.state.surveyState.opinion };
                    Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
                    fetch(url,
                        {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                "X-CSRF-TOKEN": csrfToken //sending token with request
                            },
                            contentType: "application/json; charset=utf-8",
                            credentials: 'include'
                        }
                    )
                        .then(res => res.json())
                        .then(res => {
                            console.log(res);
                        })
                        .catch(error => {
                            console.error(error);
                        });