后端我使用aspnetcore webapi,在从前端发送登录凭据并在后端进行身份验证后,我在cookie中添加csrf令牌,然后在前端获取并添加其他请求作为标头,但它无法验证,它继续检查 .AspNetCore.Antiforgery.JREqX-HygdI,而不是我在标头中传递的那个
public class CsrfValidationMiddleware
{
private readonly IAntiforgery _antiforgery;
private readonly RequestDelegate _next;
public CsrfValidationMiddleware(RequestDelegate next, IAntiforgery antiforgery)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_antiforgery = antiforgery ?? throw new ArgumentNullException(nameof(antiforgery));
}
public async Task InvokeAsync(HttpContext context)
{
var isGetRequest = string.Equals("GET", context.Request.Method, StringComparison.OrdinalIgnoreCase);
if (context.Request.Path == "/v1/api/login")
{
// Obtain and store anti-forgery tokens, including setting the cookie
var antiforgeryTokens = _antiforgery.GetAndStoreTokens(context);
// Access the CSRF token
var csrfToken = antiforgeryTokens.RequestToken;
// Add CSRF token to response headers
context.Response.Cookies.Append("XSRF-TOKEN", csrfToken, new CookieOptions
{
HttpOnly = false,
SameSite = SameSiteMode.None, // Adjust based on your requirements
Secure = true // If your site is served over HTTPS
});
}
// Validate anti-forgery token for non-GET requests
if (!isGetRequest && context.Request.Path != "/v1/api/login")
{
await _antiforgery.ValidateRequestAsync(context);
}
// Call the next middleware in the pipeline
await _next(context);
}
}
React typescript 调用 api
static api() {
const jwtToken = localStorage.getItem('token')
let token = Cookies.get("XSRF-TOKEN");
console.log('maq',token)
return axios.create({
baseURL: process.env.BaseASE_URL,
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
Authorization: 'Bearer ' + jwtToken,
'X-XSRF-TOKEN':localStorage.getItem('csrf')
}
})
}
尝试过这个博客 https://dotnetcoretutorials.com/csrf-tokens-angularjsjquery-asp-net-core/
您现在将防伪令牌放入请求标头中,但错误
The required antiforgery cookie ".AspNetCore.Antiforgery.JREqX-HygdI"
表明您的api正在尝试在cookie中查找它,因此我们需要在web api中更改此行为。
我们这里有一份文件指导我们改变行为:
假设脚本在名为的请求标头中发送令牌 X-XSRF-TOKEN,配置防伪服务以查找 X-XSRF-TOKEN 标头:
builder.Services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");