Я реализовал AntiForgeryToken в своем приложении Angular / ASP.NET Core. Но я получаю ошибку Bad Request во время выполнения. Это класс AntiForgeryTokenMiddleware:
public class AntiforgeryTokenMiddleware
{
private readonly RequestDelegate _next;
private readonly IAntiforgery _antiforgery;
public AntiforgeryTokenMiddleware(RequestDelegate next, IAntiforgery antiforgery)
{
_next = next;
_antiforgery = antiforgery;
}
public Task Invoke(HttpContext context)
{
if (context.Request.Path.Value.IndexOf("/api", StringComparison.OrdinalIgnoreCase) != -1)
{
var tokens = _antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions { HttpOnly = false });
}
return _next(context);
}
}
public static class AntiforgeryTokenMiddlewareExtensions
{
public static IApplicationBuilder UseAntiforgeryToken(this IApplicationBuilder builder)
{
return builder.UseMiddleware<AntiforgeryTokenMiddleware>();
}
}
А также у меня есть HttpInterceptor для AntiForgeryToken:
import { Injectable } from '@angular/core';
import { HttpRequest, HttpInterceptor, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AddCsrfHeaderInterceptorService implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const requestToken = this.getCookieValue('XSRF-TOKEN');
return next.handle(req.clone({
headers: req.headers.set('X-XSRF-TOKEN', requestToken)
}));
}
private getCookieValue(cookieName: string) {
const allCookies = decodeURIComponent(document.cookie).split('; ');
for (let i = 0; i < allCookies.length; i++) {
const cookie = allCookies[i];
if (cookie.startsWith(cookieName + '=')) {
return cookie.substring(cookieName.length + 1);
}
}
return '';
}
}
Кроме того, методы API украшены [ValidateAntiForgeryToken]:
[AllowAnonymous]
[ValidateAntiForgeryToken]
[HttpGet("IncrementVisit")]
public async Task<IActionResult> IncrementVisit()
{
var result = await _brandService.IncrementWebSiteVisit();
return Ok(result);
}
Когда я изменяю [ValidateAntiForgeryToken] на [IgnoreAntiForgeryToken], ошибки исчезают. ![enter image description here](https://i.stack.imgur.com/bFJHj.png)