gpt4 book ai didi

linux - 我如何跨 linux 服务器处理 ValidateAntiForgeryToken

转载 作者:IT王子 更新时间:2023-10-29 00:19:55 26 4
gpt4 key购买 nike

我已经在一些负载平衡的 Linux 服务器上部署了一个 asp.net 核心应用程序。由于 ValidateAntiForgeryToken 属性失败(如果 POST 没有返回到与生成我的表单的机器相同的机器),我在将表单发布到路由时收到错误消息。

对于 Windows 和 .Net classic,我知道要匹配 web.configmachine.config 文件中的 MachineKey 属性。

那么,我如何在 Linux 主机上实现相同的目的并允许来自一台服务器的 token 在另一台服务器上进行验证?

最佳答案

因此,当您调用 services.addMvc() 时,会自动添加防伪支持。您可以通过调用 services.AddAntiforgery(opts => "your options") 来更改基本配置。

在幕后, token 受 ASP.Net Core Data Protection library 保护(github repo here)。默认情况下,我认为这是在内存中,因此生成的 key ,然后用于 token 保护,不会在多个/云服务器场景中共享。

解决方案

因此,要共享防伪 token ,您可以设置具有共享位置的数据保护服务。数据保护库附带的默认项是:

//File system
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(@"\\some\shared\directory\"));

//Registry
services.AddDataProtection()
.PersistKeysToRegistry(Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Sample\keys"));

然后有一些默认设置可以更好地共享存储:

//redis
var redis = ConnectionMultiplexer.Connect("my-redis-url");
services.AddDataProtection()
.PersistKeysToRedis(redis, "DataProtection-Keys");

//Azure
services.AddDataProtection()
.PersistKeysToAzureBlobStorage(new Uri("blob-URI"));

我还从 github thanks to a github user named CL0SeY 找到(并使用了!)AWS S3 存储选项.

更新:Amazon 也发布了他们自己的使用 AWS SSM 参数存储的实现。 Github repo here .用于测试

默认情况下, token 的有效期为 90 天。这可以在您添加服务时设置。因此,获得简单测试解决方案的一种方法是为文件系统生成具有较长生命周期的 key ,然后将该 token 部署到服务器上的已知位置。然后从该位置设置数据保护,但告诉它永远不要生成新 key :

//generate a test key with this in a test app or whatever: 
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(@"c:\temp\"))
.SetDefaultKeyLifetime(TimeSpan.MaxValue);


// then use that key in your app:
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(@"\some\allowed\directory"))
.DisableAutomaticKeyGeneration();

在 Linux 上

当托管在 Linux 上时,所有这些都应该可以正常工作,唯一的警告是您不应该引用 Windows 驱动器或位置(duh)。我也不是 100% 确定如果您尝试注册表选项会发生什么...

关于linux - 我如何跨 linux 服务器处理 ValidateAntiForgeryToken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43860631/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com