OpenIddict:两个或更多服务实例计数时出现 401 错误

OpenIddict: 401 errors when two or more service instance count

我在使用 OpenIddict 保护的 Service Fabric 集群中有一个带有 Angular2 UI 运行 的 .NET Core 应用程序。我按照这个例子:https://github.com/openiddict/openiddict-samples/tree/master/samples/RefreshFlow

当我只有一个无状态 .NET Core 应用程序实例时,它工作得很好。当我将实例数增加到两个时,身份验证失败并且我收到一堆 401 错误。似乎我收到的令牌仅适用于该特定实例,而在另一个实例上被拒绝。 我想我明白为什么会这样,但我不确定如何解决它。

如有任何帮助,我们将不胜感激。

OpenIddict 依靠 ASP.NET Core Data Protection stack 生成和保护其授权代码、刷新令牌和访问令牌(除非您明确选择 JWT 作为访问令牌格式)。

为确保可以跨实例读取这些令牌,您必须配置 ASP.NET Core Data Protection 以共享相同的密钥环。如果您需要有关此过程的更多信息,我建议您阅读 the related documentation on Microsoft's website

我通过查看这个解决了这个问题:https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/implementation/key-storage-providers#azure-and-redis

以下是我采取的基本步骤:

  1. 创建一个 blob 存储帐户来存储共享密钥。

  2. 将以下代码添加到您的 Startup.cs:

var storageAccount = CloudStorageAccount.Parse("blob storage connection string");

//Create the blob client object.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

//Get a reference to a container to use for the sample code, and create it if it does not exist.
CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");
container.CreateIfNotExists();

services.AddDataProtection()
    .SetApplicationName("MyApplication")
    .PersistKeysToAzureBlobStorage(container, "myblobname");

就是这样。