IdentityServer4报错Unknown client or not enabled: oauthClient怎么解决?
IdentityServer4搭建SSO报错Unknown client问题
我这段时间一直在尝试基于IdentityServer4搭建SSO项目,但运行时遇到如下错误:
Sso.Application.CentralHandler: Information: AuthenticationScheme: central was challenged. IdentityServer4.Hosting.IdentityServerMiddleware: Information: Invoking IdentityServer endpoint: IdentityServer4.Endpoints.AuthorizeEndpoint for /connect/authorize IdentityServer4.Validation.AuthorizeRequestValidator: Error: Unknown client or not enabled: oauthClient IdentityServer4.Endpoints.AuthorizeEndpoint: Error: Request validation failed IdentityServer4.Endpoints.AuthorizeEndpoint: Information: { "SubjectId": "anonymous", "RequestedScopes": "", "PromptMode": "", "Raw": { "client_id": "oauthClient", "scope": "weatherforecasts.read", "response_type": "code", "redirect_uri": "https://localhost:44375/signin-central", "code_challenge": "Rdi0rU5OkG1gWzh9xfvOxbZLiGbDHqujbMzl9d3u7Qs", "code_challenge_method": "S256", "state": "CfDJ8PC7ZLg_v2RDsl0VaXUuuT_-sT-at-LgQD1krwu8LESVXDKkQxQd8_eUQZJqOiGREAzBtfZ4U9X0BJDIn15AvYXKR2omUEBW5LzJm1Vz3ykaScc_kC89f6hCimDBmqCAdUOF0wnEn8FfDD8GPJtPBgxqoqrCNnyGKxh58XOIa85sN-zDSU5Oa73pzKt5FrFIkBCqUOfpCM_KZajZR_3DWFNCbwn8tS-XR0of7ga72XDILC--N9bCqA2eIlTSxf9HHPXmmLninU1ri7RM-XMsOzH__mtQQPOXCuaHw3Q0Nkedmpj4NaTCdcB1k55IdsX1eLrub8ptagCWzMIzXcYIWlJc74Zj-_H2uDZE4M-Blbdr" } }
我已经在Stack Overflow上查找了一整天的解决方案,仍然没有定位到问题原因。
身份提供方项目Startup配置代码
services .AddDbContext<SsoCentralContext>(); //.AddScoped<Repositories.IAccountRepository, Repositories.AccountRepository>(); services.AddIdentity<IdentityUser, IdentityRole>() .AddEntityFrameworkStores<SsoCentralContext>(); var isb = services.AddIdentityServer(); isb .AddInMemoryClients(new List<Client> { new Client { ClientId = "oauthClient", ClientName = "oauthClient", AllowedGrantTypes = GrantTypes.CodeAndClientCredentials, Enabled = true, ClientSecrets = new List<Secret> {new Secret("SuperSecretPassword".Sha256())}, // change me! AllowedScopes = new List<string> {"weatherforecasts.read"}, RedirectUris = new List<string> { "https://localhost:44375/signin-central" }, } }) .AddInMemoryIdentityResources(new List<IdentityResource> { new IdentityResources.OpenId(), new IdentityResources.Profile(), new IdentityResources.Email(), new IdentityResource { Name = "role", UserClaims = new List<string> {"role"} } }) .AddInMemoryApiResources(new List<ApiResource> { new ApiResource { Name = "api1", DisplayName = "API #1", Description = "Allow the application to access API #1 on your behalf", Scopes = new List<string> { "weatherforecasts.read", "weatherforecasts.write"}, ApiSecrets = new List<Secret> {new Secret("ScopeSecret".Sha256())}, UserClaims = new List<string> {"role"} } }) .AddInMemoryApiScopes(new List<ApiScope> { new ApiScope("weatherforecasts.read", "Read Access to API #1"), new ApiScope("weatherforecasts.write", "Write Access to API #1") }) .AddTestUsers(new List<IdentityServer4.Test.TestUser> { new IdentityServer4.Test.TestUser { SubjectId = "5BE86359-073C-434B-AD2D-A3932222DABE", Username = "Pieterjan", Password = "password", Claims = new List<System.Security.Claims.Claim> { new System.Security.Claims.Claim(IdentityModel.JwtClaimTypes.Email, "pieterjan@example.com"), new System.Security.Claims.Claim(IdentityModel.JwtClaimTypes.Role, "admin") } } }) .AddDeveloperSigningCredential(); isb .AddOperationalStore(options => { options.ConfigureDbContext = (builder) => builder.UseInMemoryDatabase("SsoCentral"); }) .AddConfigurationStore(options => { options.ConfigureDbContext = (builder) => builder.UseInMemoryDatabase("SsoCentral"); }); isb.AddAspNetIdentity<IdentityUser>();
上述配置代码确认会被执行,按道理oauthClient客户端应该已经注册,且明确设置了Enabled=true处于启用状态。
业务应用项目Startup认证配置代码
services .AddAuthentication(options => { }) .AddOAuth<CentralOptions, CentralHandler>("central", options => { options.ClaimsIssuer = "https://localhost:44359"; // This is the URL of the IdentityProvider options.SaveTokens = true; options.ClientId = "oauthClient"; options.ClientSecret = "SuperSecretPassword"; options.Scope.Add("weatherforecasts.read"); options.UsePkce = true; });
请问这个错误要怎么修复?有没有人知道问题出在哪里?另外我当前的配置基础上,还需要额外配置OpenIdConnect吗?
更新
我额外添加了接口从IS4的ClientStore中读取客户端列表:
[HttpGet("Clients")] public async Task<IActionResult> GetClients() { //var client = await clientStore.FindClientByIdAsync("SsoApplicationClient"); var _inner = (IdentityServer4.EntityFramework.Stores.ClientStore)clientStore.GetType().GetField("_inner", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(clientStore); var Context = (IdentityServer4.EntityFramework.DbContexts.ConfigurationDbContext)_inner.GetType().GetField("Context", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(_inner); var Clients = Context.Clients; return Ok(Clients); }
令我意外的是,接口返回的客户端列表完全为空:
问题解答
错误根因
你同时配置了InMemory静态配置和EF持久化存储,IdentityServer4注册EF的ConfigurationStore后会覆盖默认的InMemory配置读取逻辑,优先从EF存储中读取客户端、资源等配置。你仅在代码里定义了InMemory的配置,没有将这些配置初始化写入到EF使用的内存数据库中,所以ClientStore读不到任何客户端,才会抛出Unknown client or not enabled错误。
修复方案
二选一即可:
- 方案1:删除EF存储配置,纯用InMemory模式
移除以下代码段,IS4会直接读取你通过AddInMemoryClients等方法定义的配置:isb .AddOperationalStore(options => { options.ConfigureDbContext = (builder) => builder.UseInMemoryDatabase("SsoCentral"); }) .AddConfigurationStore(options => { options.ConfigureDbContext = (builder) => builder.UseInMemoryDatabase("SsoCentral"); }); - 方案2:保留EF存储,新增初始化逻辑
项目启动时调用初始化方法,将你定义的Clients、IdentityResources、ApiResources、ApiScopes全部写入到ConfigurationDbContext中,EF存储就可以正常读取到这些配置。
OpenIdConnect配置问题
如果仅需要实现OAuth2授权码流程访问API,当前自定义OAuthHandler的方式可以正常运行。如果需要处理OpenId Connect的身份认证逻辑(比如IdToken校验、用户身份信息自动解析等),更推荐直接使用官方的AddOpenIdConnect扩展方法,不需要自行实现Handler。
内容的提问来源于stack exchange,提问作者Pieterjan
相关产品推荐
相关产品推荐

