我正在尝试使用docker配置IdentityServer4,但无法使其工作。首先,我以身份服务器文档的Client Credential为例:使用Client Credentials保护API
IdentityServer 托管在端口5000上
WebApi 托管在端口5001上
在我的WebApi文件的Configure方法中,Startup.cs我做了以下事情(问题可能在这里):
Configure
Startup.cs
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions { Authority = "http://web:5000", RequireHttpsMetadata = false, ApiName = "api1" });
客户 和客户
// Everything is fine here... var disco = await DiscoveryClient.GetAsync("http://localhost:5000"); var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret"); var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api"); // This does not work var client = new HttpClient(); client.SetBearerToken(tokenResponse.AccessToken); var response = await client.GetAsync("http://localhost:5001/identity");
问题可能出在我的WebApi中:
1)如果我将权限设置为localhost:5000,则会收到内部服务器错误:“无法从以下位置获取配置:’ http:// localhost:5000 / .well-known / openid-configuration ‘”,因为localhost :5000在此容器中未知
2)如果将权限设置为http:// web:5000,则会收到授权错误:“颁发者验证失败。颁发者:’ http:// localhost:5000 ‘。不匹配:validationParameters.ValidIssuer:’ http:/ / web:5000 ‘或validationParameters.ValidIssuers”,这也很有意义,但我不知道是否可以更改授权机构名称?我也尝试IssuerUri在IdentityServer项目中设置,但没有帮助
IssuerUri
网络
假设您有两个物理机器:C1和C2。每台机器都是docker主机。
C1运行身份验证容器。
C2运行WebApi容器。
在Auth dockerfile中公开端口5000时,C1:5000应该可以从C2 和 WebApi容器本身访问该地址。您可能更喜欢IP而不是DNS,这没关系。此外,您应该能够成功执行GET请求以http://C1:5000/.well- known/openid-configuration确保。
C1:5000
http://C1:5000/.well- known/openid-configuration
要实现此目标,可能会遇到很多网络问题。例如:什么会阻止在Docker容器中运行的代码连接到单独服务器上的数据库?
发行人验证
发行人验证失败
您的客户的授权URL与Auth主机名不同。缺省情况下,授权URL应等于issuer属性值(此属性在Identity Server自动发现文档响应中)。
issuer
issuer 属性值取决于客户的网络请求:
GET http://127.0.0.1:6000/.well-known/openid-configuration -> "issuer": "http://127.0.0.1:6000" GET http://localhost:6000/.well-known/openid-configuration -> "issuer": "localhost:6000"
尝试IssuerUri为开发环境设置一个常量:
services.AddIdentityServer(x => { x.IssuerUri = "foo"; })
达到恒定issuer值。这允许通过任何有效的URL(使用IP,计算机名或DNS)来调用Identity Server:
GET http://anything/.well-known/openid-configuration -> "issuer": "foo"
DiscoveryClient也验证issuer价值。这是一个简单的相等比较:
DiscoveryClient
public bool ValidateIssuerName(string issuer, string authority) { return string.Equals(issuer, authority, StringComparison.Ordinal); }
您可以通过以下方式禁用它:
DiscoveryClient.Policy.ValidateIssuerName = false;
仅供参考,IssuerUri设置,不建议用于生产环境:
IssuerUri设置将出现在发现文档中的发行者名称和已发行的JWT令牌。建议不要设置此属性,该属性从客户端使用的主机名推断发行者名称。