TheMagnificent11
TheMagnificent11

Reputation: 1456

ASP.Net Core - IdentityServer4 client credentials authorization not working

I am trying to create an admin client for IdentityServer4 (see full code at the time of posting here: https://github.com/TheMagnificent11/identity-server-admin/tree/0.0.1).

I've set-up my ID server using the standard steps outlined here: http://docs.identityserver.io/en/latest/quickstarts/7_entity_framework.html. The only difference is that I've moved the data access layer into a separate.Net Standard library.

I've created a second website that is to use client credentials. The client is configured on startup of the ID Server site (when running in debug configuration). Here is the code:

public static void InitializeDatabase(
    this IApplicationBuilder app,
    string adminApiName,
    string clientId,
    string clientSecret)
{
#if DEBUG
    using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
    {
        var appContext = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
        appContext.Database.Migrate();

        var grantContext = serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>();
        grantContext.Database.Migrate();

        var configContext = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
        configContext.Database.Migrate();

        SeedAdminClient(adminApiName, clientId, clientSecret, configContext);
    }
#endif
}

private static void SeedAdminClient(string adminApiName, string clientId, string clientSecret, ConfigurationDbContext configContext)
{
    if (!configContext.IdentityResources.Any())
    {
        foreach (var resource in DefaultData.IdentityResources)
        {
            configContext.IdentityResources.Add(resource.ToEntity());
        }
    }

    if (!configContext.ApiResources.Any())
    {
        var apiResource = new ApiResource(adminApiName, "Identity Server Admin");
        configContext.ApiResources.Add(apiResource.ToEntity());
    }

    if (!configContext.Clients.Any())
    {
        var adminClient = new Client
        {
            ClientName = "Identity Server Admin",
            ClientId = clientId,
            ClientSecrets =
                {
                    new Secret(clientSecret.Sha256())
                },
            AllowedScopes =
                {
                    adminApiName
                },
            AllowedGrantTypes = GrantTypes.ClientCredentials,
            Claims =
                {
                    new Claim(AdminClientClaims.ManageUsersType, AdminClientClaims.ManageUsersValue)
                }
        };

        configContext.Clients.Add(adminClient.ToEntity());
    }

    configContext.SaveChanges();
}

I can obtain a token using the client credentials. However, using the token to call the client API unexpectedly receives a 404 (the Postman collection for the requests is available here: https://github.com/TheMagnificent11/identity-server-admin/blob/0.0.1/postman_collection.json).

This is the API output from the client API:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 POST https://localhost:4001/users application/json 151
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
      Executing endpoint 'IdentityServer.Controllers.Users.UsersController.Post (IdentityServer.Admin)'
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Route matched with {action = "Post", controller = "Users"}. Executing action IdentityServer.Controllers.Users.UsersController.Post (IdentityServer.Admin)
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
      Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[12]
      AuthenticationScheme: Identity.Application was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action IdentityServer.Controllers.Users.UsersController.Post (IdentityServer.Admin) in 69.589ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
      Executed endpoint 'IdentityServer.Controllers.Users.UsersController.Post (IdentityServer.Admin)'
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 284.0746ms 302
info: Microsoft.AspNetCore.Server.Kestrel[32]
      Connection id "0HLL47CTA76NM", Request id "0HLL47CTA76NM:00000001": the application completed without reading the entire request body.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET https://localhost:4001/Account/Login?ReturnUrl=%2Fusers

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 25.5762ms 404

Does anyone know what I'm doing wrong?

Upvotes: 1

Views: 1464

Answers (2)

emilol
emilol

Reputation: 171

Looks very similar to this issue: https://github.com/IdentityServer/IdentityServer4/issues/2406

I pulled it down and tried this:

services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
    .AddJwtBearer(options =>
    {
        // etc..

Which got me a 403 rather than a 404

Upvotes: 3

Bishal Sharma
Bishal Sharma

Reputation: 51

If you are receiving a 404 response, make sure that you are using the correct GET/POST/PUT request. Using GET method on a route that allows POST request only will result in 404 as well, even if the route URL is correct.

Upvotes: 0

Related Questions