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

标签 linux asp.net-core .net-core antiforgerytoken

我已经在一些负载平衡的 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/

相关文章:

c# - conditional-middleware-in-aspnet-core 在 asp.net core 1.1 中不工作

c# - WinHttp异常 : The connection with the server was terminated abnormally

c# - 无法解析非 ASP.NET Core 应用程序中类型 IOptions [DataAccessConfiguration] 的服务

c# - 如何在 C# .Net 核心的工厂设计模式中使用反射

csv - 将应用程序移动到新服务器后,使用 CsvHelper 库生成的 CSV 文件中缺少逗号/分隔符

c - 尝试写入 struct ip 时出现错误 “dereferencing pointer to incomplete type”

c - 检测影子密码文件是否正在使用的最佳方法

linux bash 脚本 -> 更新远程 mysql 表 -> 错误 [0m

linux - 将 BlueZ 堆栈用作外围设备时的有效载荷错误

html - 如何制作自适应 iFrame 高度?