Dla potomnych, udało mi się w końcu zaimplementować AntiForgery
token dla wywołania Fetch. Było to bardziej kompleksowe zadanie niż się spodziewałem. Też może być inaczej dla różnych wersji ASP.NET. Poniżej rozwiązanie dla ASP.NET Core 2.1.
W Startup.cs
dodajemy:
Kopiuj
//znalazłem konfigurację w jakimś tutku, już go dawno zamknąłem, czasami można spotkać z X-XSRF-TOKEN, dla tego nie testowałem
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(); //podobno musi być wstawiane przed tym
Moja metoda POST
w SurveyController.cs
wygląda tak:
Kopiuj
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddComment(Survey survey)
{
if (survey == null)
{
return BadRequest();
}
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
return Ok();
}
W pliku JS
, u mnie Dialog.js
należy dodać funkcję pobierającą ciasteczka:
Kopiuj
//podobnie jak w tutorialu 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]);
}
następnie przy odpaleniu Fetch
:
Kopiuj
var csrfToken = getCookie("CSRF-TOKEN");
//url dla fetch, rekonemdowany sposób w dokumentacji
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 //wysyłamy token wraz z żądaniem
},
contentType: "application/json; charset=utf-8",
credentials: 'include'
}
)
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch(error => {
console.error(error);
});