Asp.net

asp.net core 2.0中的機器密鑰?

  • January 25, 2021

我有相同的 asp.net core 2 應用程序在 2 個不同的伺服器上執行,但使用相同的數據庫來儲存使用者等。

問題是,如果我在一台伺服器上創建並設置使用者密碼,另一台執行相同應用程序的伺服器會返回無效密碼,反之亦然。

幾年前我在使用 asp.net 4 應用程序時遇到了這個問題,我通過為兩個應用程序設置相同的機器密鑰來修復它。

我聽說過數據保護 api,但我找不到在哪裡告訴它使用相同的加密密鑰,相反,我找到了讓我感到困惑的複雜範例,我所需要的只是讓兩台伺服器都了解彼此的加密。

您可以將一台伺服器作為主伺服器,將一台伺服器作為輔助伺服器。在輔助伺服器中禁用自動密鑰生成

using Microsoft.AspNetCore.DataProtection;

public void ConfigureServices(IServiceCollection services)
{
    services.AddDataProtection().DisableAutomaticKeyGeneration();
}

或者你可以將它們持久化到 Redis

public void ConfigureServices(IServiceCollection services)
{
   // sad but a giant hack :(
   // https://github.com/StackExchange/StackExchange.Redis/issues/410#issuecomment-220829614
   var redisHost = Configuration.GetValue<string>("Redis:Host");
   var redisPort = Configuration.GetValue<int>("Redis:Port");
   var redisIpAddress = Dns.GetHostEntryAsync(redisHost).Result.AddressList.Last();
   var redis = ConnectionMultiplexer.Connect($"{redisIpAddress}:{redisPort}");

   services.AddDataProtection().PersistKeysToRedis(redis, "DataProtection-Keys");
   services.AddOptions();

   // ...
}

詳細的文章可在同一

http://www.tugberkugurlu.com/archive/asp-net-core-authentication-in-a-load-balanced-environment-with-haproxy-and-redis

PS:上面貼的程式碼來自同一篇文章,所以如果連結掛了,答案還是完整的

引用自:https://stackoverflow.com/questions/46860603