Search code examples
asp.net-coreidentityserver4asp.net-core-identity

IdentityServer4 - Error: Unknown client or not enabled: oauthClient


I've been trying to setup a project with IdentityServer4 for a while. However I'm getting the following error:

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"
  }
}

I've been looking on SO for how to solve this error for the entire day, but I can't figure out what's wrong with it.

This is the code in the Startup of the IdentityProvider project:

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, "[email protected]"),
                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>();

The above code is definitely being called, so the oauthClient should exist for sure. Also the client is definitely enabled.

This is the code in Startup of the Identity project:

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;
    });

How can I fix this error? Would anyone know how to figure out what's wrong here?

Also would I still need to use OpenIdConnect on top of what's been configured here?

Update:

I've added a call just to get the clients from the 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);
}

To my amazement, what I get from this is an entirely empty list:

No oauth clients are returned from IdentityServer4


Solution

  • Alright, so when you have the following configuration:

    services.AddIdentityServer()
        ...
        .AddOperationalStore(options =>
        {
            options.ConfigureDbContext = (builder) => builder.UseInMemoryDatabase("SsoCentral");
        })
        .AddConfigurationStore(options =>
        {
            options.ConfigureDbContext = (builder) => builder.UseInMemoryDatabase("SsoCentral");
        })
    

    The InMemoryClients don't exist anymore. Just commented it out and it seems to be working now.