gpt4 book ai didi

c# - 向 Identity Server 4 添加自定义客户端服务后出现 CORS 错误

转载 作者:太空宇宙 更新时间:2023-11-03 20:57:59 24 4
gpt4 key购买 nike

我关注了 Identity Server 4文档并在本地创建了一个工作测试实例。然后我在 this tutorial 之后添加了一个示例 Javascript 客户端.这一切都很好,同时仍在使用测试用户和客户端。

我现在想开始将测试数据分解为生产就绪服务。我想我应该从我的客户开始。这是我的 Startup 中的 ConfigureServices 方法中的 Identity Server 设置代码:

var builder = services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
//.AddInMemoryClients(Config.GetClients())
.AddTestUsers(Config.GetUsers());

builder.Services.AddTransient<IdentityServer4.Stores.IClientStore, CustomClientStore>();

从字面上看,我在这里所做的唯一更改是注释掉 AddInMemoryClients 行并添加注册新客户端存储的最后一行。现在所有这些 CustomClientStore 类所做的就是复制 Config.GetClients() 测试数据。

但是,当我现在运行我的演示 Javascript 应用程序并单击我的登录按钮时,我现在收到以下 Javascript 错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:54458/.well-known/openid-configuration. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

http://localhost:54458显然是我的 IS4 实例。我没有触及我的 CORS 配置,如果我注释掉上面的 AddTransient 行并恢复 AddInMemoryClients 行,一切都会再次正常。

谁能帮我理解一下?

最佳答案

我通过查看 Identity Server 自己的代码找到了答案。事实证明,在使用 AddInMemoryClients 扩展注册测试客户端存储时,Identity Server 也在同时实现 CORS 策略。可以看到this code here .

此 CORS 策略使用另一个内存中实现,这次是 ICorsPolicyService。此实现采用已配置客户端的 AllowedCorsOrigins 属性来确定是否允许请求源。

所以我的解决方案是创建这个扩展方法...

public static IIdentityServerBuilder AddCustomCorsPolicy(this IIdentityServerBuilder builder)
{
var existingCors = builder.Services.Where(x => x.ServiceType == typeof(ICorsPolicyService)).LastOrDefault();
if (existingCors != null &&
existingCors.ImplementationType == typeof(DefaultCorsPolicyService) &&
existingCors.Lifetime == ServiceLifetime.Transient)
{
builder.Services.AddTransient<ICorsPolicyService, CustomCorsPolicyService>();
}

return builder;
}

...然后实现 CustomCorsPolicyService 以根据我的客户群中的设置检查请求源,然后将 AddCustomCorsPolicy 添加到我的 Identity Server 设置中。

关于c# - 向 Identity Server 4 添加自定义客户端服务后出现 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48470352/

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