我不知道如何使用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);
});发布于 2018-11-27 00:21:53
我的最后解决方案。在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 in 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文件中,需要创建函数获取cookies:
//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);
});https://stackoverflow.com/questions/53469047
复制相似问题