【问题标题】:Duende.IdentityServer from Blazor WebAssembly App protecting ASP.NET Core API using Client Credentials with custom allowed scope - invalid_scope来自 Blazor WebAssembly App 的 Duende.IdentityServer 使用具有自定义允许范围的客户端凭据保护 ASP.NET Core API - invalid_scope
【发布时间】:2022-10-13 17:10:04
【问题描述】:

我有一个用Microsoft Visual Studio 创建的Blazor WebAssembly App,具有以下规格:Target Framework .NET 6.0Authentication Type Individual AccountsASP.NET Core Hosted

使用这个答案,我已经能够添加客户端凭据流

https://stackoverflow.com/a/67324222/3850405

我从appsettings.json 中删除了这个:

"Clients": {
  "WebApplication4.Client": {
    "Profile": "IdentityServerSPA"
  }
}

编辑Startup.csProgram.cs

services.AddIdentityServer()
    .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options =>
    {
        options.Clients.AddIdentityServerSPA("WebApplication4.Client", builder =>
        {
            builder.WithRedirectUri("/authentication/login-callback");
            builder.WithLogoutRedirectUri("/authentication/logout-callback");
        });
        options.Clients.Add(new Duende.IdentityServer.Models.Client
        {
            ClientId = "WebApplication4.Integration",
            AllowedGrantTypes = { GrantType.ClientCredentials },
            ClientSecrets = { new Secret("MySecretValue".Sha256()) },
            AllowedScopes = { "WebApplication4.ServerAPI"}
        });
    });

此请求将起作用:

POST /connect/token HTTP/1.1
Host: localhost:44397
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials&client_id=WebApplication4.Integration&client_secret=MySecretValue&scope=WebApplication4.ServerAPI

但是我希望这个客户有自己的AllowedScopes。如果我然后将AllowedScopes = { "WebApplication4.ServerAPI"} 更改为AllowedScopes = { "WebApplication4.IntegrationAPI"},当然还要修改请求。

然后服务器响应:

{
    "error": "invalid_scope"
}

如果我查看日志记录,我会得到以下历史记录:

info: Duende.IdentityServer.Hosting.IdentityServerMiddleware[0]
      Invoking IdentityServer endpoint: Duende.IdentityServer.Endpoints.TokenEndpoint for /connect/token
info: Duende.IdentityServer.Events.DefaultEventService[0]
      {
        "ClientId": "WebApplication4.Integration",
        "AuthenticationMethod": "SharedSecret",
        "Category": "Authentication",
        "Name": "Client Authentication Success",
        "EventType": "Success",
        "Id": 1010,
        "ActivityId": "80000009-0014-d600-b63f-84710c7967bb",
        "TimeStamp": "2022-09-22T09:30:31Z",
        "ProcessId": 17768,
        "LocalIpAddress": "::1:44397",
        "RemoteIpAddress": "::1"
      }
fail: Duende.IdentityServer.Validation.DefaultResourceValidator[0]
      Scope WebApplication4.IntegrationAPI not found in store or not supported by requested resource indicators.
fail: Duende.IdentityServer.Validation.TokenRequestValidator[0]
      Invalid scopes requested, {
        "ClientId": "WebApplication4.Integration",
        "GrantType": "client_credentials",
        "AuthorizationCode": "********",
        "RefreshToken": "********",
        "Raw": {
          "grant_type": "client_credentials",
          "client_id": "WebApplication4.Integration",
          "client_secret": "***REDACTED***",
          "scope": "WebApplication4.IntegrationAPI"
        }
      }
info: Duende.IdentityServer.Events.DefaultEventService[0]
      {
        "ClientId": "WebApplication4.Integration",
        "Endpoint": "Token",
        "GrantType": "client_credentials",
        "Error": "invalid_scope",
        "Category": "Token",
        "Name": "Token Issued Failure",
        "EventType": "Failure",
        "Id": 2001,
        "ActivityId": "80000009-0014-d600-b63f-84710c7967bb",
        "TimeStamp": "2022-09-22T09:30:31Z",
        "ProcessId": 17768,
        "LocalIpAddress": "::1:44397",
        "RemoteIpAddress": "::1"
      }

我随身携带的是这样的:

Scope WebApplication4.IntegrationAPI not found in store or not supported by requested resource indicators.

然后我查看了这些指南:

https://github.com/IdentityServer/IdentityServer4/issues/4632#issuecomment-654685880

https://docs.duendesoftware.com/identityserver/v5/quickstarts/1_client_credentials/

因此,我添加了以下代码:

public static class Config
{
    public static IEnumerable<ApiScope> ApiScopes =>
        new List<ApiScope>
        {
        new ApiScope("WebApplication4.IntegrationAPI", "Integration API")
        };
}

services.AddIdentityServer()
    .AddInMemoryApiScopes(Config.ApiScopes)
    .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options =>...

这仍然给了我同样的错误。

然后我添加了一个新的客户列表:

public static IEnumerable<Duende.IdentityServer.Models.Client> Clients =>
    new List<Duende.IdentityServer.Models.Client>
    {
        new Duende.IdentityServer.Models.Client
        {
            ClientId = "WebApplication4.Integration",
            AllowedGrantTypes = { GrantType.ClientCredentials },
            ClientSecrets = { new Secret("MySecretValue".Sha256()) },
            AllowedScopes = { "WebApplication4.IntegrationAPI" },
        }
    };

AddApiAuthorization 中删除了旧客户端并改用以下代码:

services.AddIdentityServer()
    .AddInMemoryApiScopes(Config.ApiScopes)
    .AddInMemoryClients(Config.Clients)
    .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options => ...

这在请求令牌时给了我一个新错误:

{
    "error": "invalid_client"
}

日志:

info: Duende.IdentityServer.Hosting.IdentityServerMiddleware[0]
      Invoking IdentityServer endpoint: Duende.IdentityServer.Endpoints.TokenEndpoint for /connect/token
info: Duende.IdentityServer.Events.DefaultEventService[0]
      {
        "ClientId": "WebApplication4.Integration",
        "Category": "Authentication",
        "Name": "Client Authentication Failure",
        "EventType": "Failure",
        "Id": 1011,
        "Message": "Unknown client",
        "ActivityId": "8000000a-0016-e700-b63f-84710c7967bb",
        "TimeStamp": "2022-09-22T09:54:08Z",
        "ProcessId": 10676,
        "LocalIpAddress": "::1:44397",
        "RemoteIpAddress": "::1"
      }
fail: Duende.IdentityServer.Validation.ClientSecretValidator[0]
      No client with id 'WebApplication4.Integration' found. aborting

如果我查看 https://localhost:44397/.well-known/openid-configuration,无论配置如何,我都只会在 scopes_supported 中看到 WebApplication4.ServerAPI

我想这样做,以便以后可以添加这样的策略:

services.AddAuthorization(options =>
{
    options.AddPolicy("IntegrationApiScope", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireClaim("scope", "WebApplication4.IntegrationAPI");
    });
});

这意味着我只希望客户端凭据流获得WebApplication4.IntegrationAPI 的范围,并且我不希望授权代码授予、通过 (authorization_code) 的正常登录流具有此范围。

【问题讨论】:

    标签: c# .net .net-core asp.net-identity duende-identity-server


    【解决方案1】:

    这将起作用:

    services.AddIdentityServer()
        .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options =>
        {
            options.ApiScopes.Add(new ApiScope("scope1"));
            options.Clients.AddIdentityServerSPA("WebApplication4.Client", builder =>
            {
                builder.WithRedirectUri("/authentication/login-callback");
                builder.WithLogoutRedirectUri("/authentication/logout-callback");
            });
            options.Clients.Add(new Duende.IdentityServer.Models.Client
            {
                ClientId = "WebApplication4.Integration",
                AllowedGrantTypes = { GrantType.ClientCredentials },
                ClientSecrets = { new Secret("MySecretValue".Sha256()) },
                AllowedScopes = { "scope1" }
            });
        });
    

    但是WebApplication4.Integration 仍然可以请求范围WebApplication4.ServerAPI 并获得一个令牌。

    使用以下代码:

    services.AddIdentityServer()
        .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options =>
        {
            options.ApiScopes.Add(new ApiScope("scope1"));
            options.ApiScopes.Add(new ApiScope("scope2"));
            options.Clients.Add(new Duende.IdentityServer.Models.Client
            {
                ClientId = "WebApplication4.Integration",
                AllowedGrantTypes = { GrantType.ClientCredentials },
                ClientSecrets = { new Secret("MySecretValue".Sha256()) },
                AllowedScopes = { "scope1" }
            });
        });
    

    WebApplication4.Integration 可以使用范围 WebApplication4.ServerAPIscope1 获取令牌,但不能使用 scope2

    有关更多信息,请参阅此问题:

    https://github.com/dotnet/aspnetcore/issues/44122

    【讨论】:

      猜你喜欢
      • 2021-09-08
      • 2019-11-01
      • 2021-01-03
      • 2019-08-16
      • 2021-04-14
      • 2020-03-25
      • 2019-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多