ASP.NET Core React SPA应用程序中的ValidateAntiForgeryToken [英] ValidateAntiForgeryToken in an ASP.NET Core React SPA Application
问题描述
我正在尝试使用框架的工具向ASP.NET Core React SPA添加一些简单的CSRF验证.该应用程序本质上是一个create-react-app设置(带有根元素的单个index.html,所有其他内容都从捆绑的JavaScript中加载).
I'm trying to use the framework's tools to add some simple CSRF validation to an ASP.NET Core React SPA. The application itself is essentially a create-react-app setup (a single index.html with a root element and everything else is loaded in from bundled JavaScript).
使用在此,我在Startup.ConfigureServices
中设置了以下内容:
Tinkering with some information found on links such as this one, I've set the following in my Startup.ConfigureServices
:
services.AddAntiforgery(options => options.Cookie.Name = "X-CSRF-TOKEN");
并在我的Chrome工具中确认已设置cookie.如果省略上面的行,则仍会使用部分随机化的名称来设置cookie,例如:.AspNetCore.Antiforgery.RAtR0X9F8_w
设置cookie的任何一种方式.我还确认,每当我重新启动整个应用程序时,cookie值都会更新,因此框架会主动设置此cookie.
And confirmed in my Chrome tools that the cookie is being set. If I omit the above line, a cookie is still set with a partially randomized name, such as: .AspNetCore.Antiforgery.RAtR0X9F8_w
Either way the cookie is being set. I've also confirmed that any time I re-start the whole application the cookie value is updated, so the framework is actively setting this cookie.
在我的Chrome工具中观察网络请求后,我确认Cookie是应AJAX请求发送到服务器的.在服务器上放置一个断点并在控制器操作中观察Request.Cookies
值也可以确认这一点.
Observing network requests in my Chrome tools, I confirm that the cookie is being sent to the server on AJAX request. Placing a breakpoint on the server and observing the Request.Cookies
value in a controller action also confirms this.
但是,如果我用[ValidateAntiForgeryToken]
装饰任何此类AJAX请求的操作,则响应始终为空400.
However, if I decorate any such AJAX requested action with [ValidateAntiForgeryToken]
then the response is always an empty 400.
我在某处错过了配置步骤吗?也许action属性的位置错误,我需要使用其他验证吗?
Is there a configuration step I've missed somewhere? Perhaps the action attribute is looking in the wrong place and I need to use a different validation?
推荐答案
我只是检查日志并发现有异常:
I just inspect the log and find out there's an exception:
Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException:所需的防伪cookie".AspNetCore.Antiforgery.HPE6W9qucDc"不存在. 在Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery.ValidateRequestAsync(HttpContext httpContext) 在Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ValidateAntiforgeryTokenAuthorizationFilter.OnAuthorizationAsync(AuthorizationFilterContext context)中
Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The required antiforgery cookie ".AspNetCore.Antiforgery.HPE6W9qucDc" is not present. at Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery.ValidateRequestAsync(HttpContext httpContext) at Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ValidateAntiforgeryTokenAuthorizationFilter.OnAuthorizationAsync(AuthorizationFilterContext context)
它表示您忘记配置cookie名称:
public void ConfigureServices(IServiceCollection services)
{
//services.AddAntiforgery();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
}
所以我只添加如下配置:
So I just add a configuration as below :
public void ConfigureServices(IServiceCollection services)
{
services.AddAntiforgery(o => {
o.Cookie.Name = "X-CSRF-TOKEN";
});
// ...
}
它现在可以工作.
此外,如果您想省略services.AddAntiforgery(options => options.Cookie.Name = "X-CSRF-TOKEN");
行,则可以使用内置的antiforgery.GetAndStoreTokens(context)
方法发送cookie:
Also, if you would like to omit the line of services.AddAntiforgery(options => options.Cookie.Name = "X-CSRF-TOKEN");
, you can use the built-in antiforgery.GetAndStoreTokens(context)
method to send cookie:
app.Use(next => context =>
{
if (context.Request.Path == "/")
{
//var tokens = antiforgery.GetTokens(context);
var tokens = antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append("X-CSRF-TOKEN", tokens.CookieToken, new CookieOptions { HttpOnly = false });
context.Response.Cookies.Append("X-CSRF-FORM-TOKEN", tokens.RequestToken, new CookieOptions { HttpOnly = false });
}
return next(context);
})
两者都应按预期工作.
这篇关于ASP.NET Core React SPA应用程序中的ValidateAntiForgeryToken的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!