我存储了我的 clients在 appsettings.json 文件中为我的身份服务器:
"ClientSettings": [
{
"ClientId": "TestClient1",
"RedirectUris": [ "http://localhost:5002/signin-oidc" ],
"PostLogoutRedirectUris": [ "http://localhost:5002/signout-callback-oidc" ],
"AllowedGrantTypes": [ "hybrid" ],
"AllowedScopes": [ "openid","profile","email" ],
"RequireConsent": "false",
"Enabled": "true",
"ClientSecrets": [
{
"Description": "This is the client sceret description.",
"Value": "password123"
}
]
}
],
在我的 ConfigureServices
方法中我设置了依赖注入(inject)
services.Configure<List<Client>>(config.GetSection("ClientSettings"));
我的 IClientStore
通过依赖注入(inject)获取客户端列表。当然,我需要散列客户端 secret 。为了让这个问题简单化,我编写了这段代码,假设我只有一个客户端和一个客户端密码。
public ClientConfigFileStore(IOptions<List<Client>> options)
{
var jsonClient = options.Value[0];
Client client = new Client()
{
ClientId = jsonClient.ClientId,
RedirectUris = jsonClient.RedirectUris,
PostLogoutRedirectUris = jsonClient.PostLogoutRedirectUris,
AllowedGrantTypes = jsonClient.AllowedGrantTypes,
AllowedScopes = jsonClient.AllowedScopes,
RequireConsent = jsonClient.RequireConsent,
Enabled = jsonClient.Enabled,
};//Works
Client client = jsonClient;//Does not work
client.ClientSecrets = new List<Secret>()
{
new Secret(jsonClient.ClientSecrets.First().Value.Sha256())
};
clients = new List<Client>() { client };
}
不知何故,我需要创建一个新的 Client
实例,但使用依赖注入(inject)创建的实例不起作用。用户在身份服务器上输入其凭据后,重定向回客户端失败并显示 Client secret validation failed for the client: TestClient1
为什么需要创建一个新实例,是否有更优雅的方式从 appsettings.json
文件加载客户端?
最佳答案
我不确定我是否理解您正在尝试做的事情或您为什么要这样做。主要是我不确定为什么要像现在这样将它们加载到 DI 中。您应该考虑在内存客户端中使用。
启动.cs
public void ConfigureServices(IServiceCollection services)
{
// configure identity server with in-memory stores, keys, clients and scopes
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients());
}
配置.cs
public class Config
{
// scopes define the API resources in your system
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API")
};
}
// clients want to access resources (aka scopes)
public static IEnumerable<Client> GetClients()
{
// client credentials client
return new List<Client>
{
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "api1" }
}
};
}
}
关于c# - Identity Server 4 使用 IConfiguration 创建客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51036851/