gpt4 book ai didi

c# - 身份服务器 4 - 停用发现端点

转载 作者:可可西里 更新时间:2023-11-01 09:13:59 25 4
gpt4 key购买 nike

我正在开发一个身份验证服务器来传送 token ,以便使用 IdentityServer4 使用我们的 API。我使用 MongoDB 作为数据库,允许用户在上面获取 token ,为了更安全,我使用自定义证书来加密 token 。这就是我的 AuthenticationServerStartup.cs 的样子:

public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

var cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "cert", "whatever.pfx"), "whatever");

services.AddIdentityServer().AddSigningCredential(cert)
.AddInMemoryApiResources(Config.Config.GetApiResources());

services.AddTransient<IUserRepository, UserRepository>();

services.AddTransient<IClientStore, ClientStore>();
services.AddTransient<IProfileService, UserProfileService>();
services.AddTransient<IResourceOwnerPasswordValidator, UserResourceOwnerPasswordValidator>();
services.AddTransient<IPasswordHasher<User.Model.User>, PasswordHasher<User.Model.User>>();

}

如您所见,我对那些执行客户端身份验证和密码验证的接口(interface)进行了自定义实现。这工作正常。

然后我用生成的 token 保护另一个应用程序,我在那里定义它必须使用IdentityServerAuthetication(localhost:5020 是我的 AuthenticationServer 正在运行)

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors("CorsPolicy");

loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = "http://localhost:5020",
RequireHttpsMetadata = false,
ApiName = "MyAPI",
RoleClaimType = JwtClaimTypes.Role
});

app.UseMvc();
}

一切正常,但是如果我关闭 AuthenticationServer 然后我从我正在保护的 API 得到这个错误:

System.InvalidOperationException: IDX10803: Unable to obtain configuration from: 'http://localhost:5020/.well-known/openid-configuration'. at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.d__24.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.d__1.MoveNext() fail: Microsoft.AspNetCore.Server.Kestrel[13]

所以看起来 API 将转到发现端点 以查看解密 token 的端点在哪里(我猜是 userinfo_endpoint)。

我的观点是:

  • 似乎发现端点用于获取有关如何使用身份验证服务器的信息(对我来说开放 API 很有意义),但在我们的例子中,我们没有开发和开放 API,因此我们的客户只是那些我们有协议(protocol),我们会提前告诉他们端点,我们很可能会通过 IP 地址进行限制。
  • 有什么方法可以停用发现端点并在 API 上设置证书以正确解密 token 。

也许我错过了完整的画面并且我在说傻话,但我很乐意理解背后的概念。提前致谢

最佳答案

可以关闭/不可用发现端点并仍然验证 token 。

您需要实现 IConfigurationManager 并将其传递给 IdentityServerAuthenticationOptions 内的 JwtBearerOptions 对象。

下面是一些示例代码:

public class OidcConfigurationManager : IConfigurationManager<OpenIdConnectConfiguration>
{
public OidcConfigurationManager()
{
SetConfiguration();
}
private OpenIdConnectConfiguration _config;
public Task<OpenIdConnectConfiguration> GetConfigurationAsync(CancellationToken cancel)
{
return Task.FromResult<OpenIdConnectConfiguration>(_config);
}
public void RequestRefresh()
{
}

private void SetConfiguration()
{
// Build config from JSON
var configJson =
@"{""issuer"":""http://localhost/id"",""jwks_uri"":""http://localhost/id/.well-known/openid-configuration/jwks"",""authorization_endpoint"":""http://localhost/id/connect/authorize"",""token_endpoint"":""http://localhost/id/connect/token"",""userinfo_endpoint"":""http://localhost/id/connect/userinfo"",""end_session_endpoint"":""http://localhost/id/connect/endsession"",""check_session_iframe"":""http://localhost/id/connect/checksession"",""revocation_endpoint"":""http://localhost/id/connect/revocation"",""introspection_endpoint"":""http://localhost/id/connect/introspect"",""frontchannel_logout_supported"":true,""frontchannel_logout_session_supported"":true,""scopes_supported"":[""openid"",""profile"",""api1"",""offline_access""],""claims_supported"":[""sub"",""name"",""family_name"",""given_name"",""middle_name"",""nickname"",""preferred_username"",""profile"",""picture"",""website"",""gender"",""birthdate"",""zoneinfo"",""locale"",""updated_at""],""grant_types_supported"":[""authorization_code"",""client_credentials"",""refresh_token"",""implicit"",""password""],""response_types_supported"":[""code"",""token"",""id_token"",""id_token token"",""code id_token"",""code token"",""code id_token token""],""response_modes_supported"":[""form_post"",""query"",""fragment""],""token_endpoint_auth_methods_supported"":[""client_secret_basic"",""client_secret_post""],""subject_types_supported"":[""public""],""id_token_signing_alg_values_supported"":[""RS256""],""code_challenge_methods_supported"":[""plain"",""S256""]}";
_config = new OpenIdConnectConfiguration(configJson);

// Add signing keys if not present in json above
_config.SigningKeys.Add(new X509SecurityKey(cert));
}
}

现在将该配置对象传递给您的 IdentityServerAuthenticationOptions 中的一些 JwtBearerOptions(有点烦人,但这是我所知道的唯一方法)

var identityServerOptions = new IdentityServerAuthenticationOptions
{
Authority = "http://localhost:5020",
RequireHttpsMetadata = false,
ApiName = "MyAPI",
RoleClaimType = JwtClaimTypes.Role,

};
var jwtBearerOptions = new JwtBearerOptions() {ConfigurationManager = new OidcConfigurationManager()};
var combinedOptions = CombinedAuthenticationOptions.FromIdentityServerAuthenticationOptions(identityServerOptions);
combinedOptions.JwtBearerOptions = jwtBearerOptions;
app.UseIdentityServerAuthentication(combinedOptions);

现在,即使 OIDC 发现端点关闭,您的 API 也能够接收 token 并验证签名。

关于c# - 身份服务器 4 - 停用发现端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43865529/

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