IdentityServer4从3.1.4升级到4.0.0后Scope无效问题排查
Let's break down why your IdentityPortal.API scope isn't being recognized post-upgrade, and walk through the fixes step by step.
1. Critical Issue: Missing ApiScopes in GetAllResourcesAsync
The primary problem lies in your CustomResourceStore implementation. In IdentityServer4 4.x, the server's metadata (including the scopes_supported list) is built from the Resources object returned by GetAllResourcesAsync. Your current code omits the ApiScopes collection entirely:
public Task<Resources> GetAllResourcesAsync() { var result = new Resources(GetAllIdentityResources(), GetAllApiResources(), null); return Task.FromResult(result); }
You're passing null for the third parameter (which expects an IEnumerable<ApiScope>). That's why your custom scope never appears in the metadata.
Fix: Update the method to include your stored ApiScopes:
public Task<Resources> GetAllResourcesAsync() { var result = new Resources(GetAllIdentityResources(), GetAllApiResources(), GetAllApiScopes()); return Task.FromResult(result); }
2. Ensure ApiScopes Exist in Your MongoDB Store
Since you're using a custom IResourceStore that pulls data from MongoDB, you need to confirm:
- A valid
ApiScopedocument forIdentityPortal.APIexists in your database. It should match the definition in yourConfig.AllowedScopes()method:new ApiScope(apiScope) // apiScope = "IdentityPortal.API" - Your
FindApiScopesByNameAsyncmethod is correctly querying for these scopes (your current implementation looks correct, but verify the data exists in MongoDB).
⚠️ Note: The .AddInMemoryApiScopes(Config.AllowedScopes()) call in your IdentityServer setup is ignored when using a custom IResourceStore. IdentityServer prioritizes your custom store over in-memory configurations, so the scope must exist in MongoDB.
3. Verify ApiResource and ApiScope Alignment
In IdentityServer4 4.x, ApiResource and ApiScope are decoupled. Double-check that:
- The
Scopesproperty on yourApiResourceexactly matches theNameof yourApiScope:new ApiResource(apiScope, "Falcon Api") { Scopes = new List<string>{apiScope}, // Matches "IdentityPortal.API" // ... claims } - Your
ApiScopeis configured with the correct name in both code and MongoDB.
Final Validation Steps
After applying these fixes:
- Restart your IdentityServer instance.
- Visit the metadata endpoint at
https://localhost:5001/.well-known/openid-configurationand confirmIdentityPortal.APIappears in thescopes_supportedarray. - Retest your React application's authentication request—IdentityServer should now correctly recognize the
IdentityPortal.APIscope.
内容的提问来源于stack exchange,提问作者San Jaisy

