【发布时间】:2024-04-18 11:15:02
【问题描述】:
我收到一条错误消息“CurlException:无法连接到服务器”
我正在尝试在客户端控制器中使用此代码访问 API:
var tokenClient = new TokenClient("http://localhost:5003/connect/token", "client", "secret");
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");
var client = new HttpClient();
client.SetBearerToken(tokenResponse.AccessToken);
var content = await client.GetStringAsync("http://localhost:5102/api/catalog/items");
ViewBag.Json = JArray.Parse(content).ToString();
return View("json");
这是客户端中的代码:
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
// options.DefaultAuthenticateScheme = "Cookies";
})
.AddCookie()
.AddOpenIdConnect(options => {
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.Authority = identityUrl.ToString();
options.SignedOutRedirectUri = callBackUrl.ToString();
options.ClientId ="client";
options.ClientSecret = "secret";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.RequireHttpsMetadata = false;
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("api1");
IdentityServer 配置中的代码:
new Client
{
ClientId = "client",
ClientSecrets = new [] { new Secret("secret".Sha256())},
AllowedGrantTypes = GrantTypes.Hybrid,
RedirectUris = { "http://localhost:5202/signin-oidc" },
PostLogoutRedirectUris = {"http://localhost:5202/signout-callback-oidc"},
AllowAccessTokensViaBrowser = false,
AllowOfflineAccess = true,
RequireConsent = true,
AlwaysSendClientClaims = true,
AlwaysIncludeUserClaimsInIdToken = true,
AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
//"MobileApi"
"api1"
}
以及Api中的代码:
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority =Configuration.GetValue<string>("IdentityUrl");
options.RequireHttpsMetadata = false;
options.ApiName = "api1";
});
所有 Url 变量都是正确的,我在其他地方使用它们没有问题。我相信问题出在 docker 上,因为 github 上有这个线程:https://github.com/aspnet/Home/issues/1975。然而,“答案”没有解释,执行起来也很模糊。有没有办法解决这个问题,以便我的客户端可以通过 docker 连接到 api?
【问题讨论】:
-
可能与实际问题正交,但您允许的客户端端口号与您在获得不记名令牌后请求数据的端口号不同。 IdentityServer 会将其作为无效请求返回给您,如果 Config.cs 与您的实际配置相同(假设您已设置数据库来保存它)
-
我相信你指的是client.getstringasync?那是api端口。
-
好的,所以我假设您更新了 AllowedRedirectUri 列表以反映这一点?因为您上面的代码显示您允许 localhost:5202 而不是 localhost:5102
-
我没有更新任何东西。 :5202 是应该重定向的 webmvc。 :5102 是 api。
标签: asp.net docker identityserver4