首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用具有自定义允许范围的客户端凭据保护Duende.IdentityServer WebAssembly应用程序- invalid_scope

使用具有自定义允许范围的客户端凭据保护Duende.IdentityServer WebAssembly应用程序- invalid_scope
EN

Stack Overflow用户
提问于 2022-09-22 10:13:58
回答 1查看 206关注 0票数 0

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

使用此答案,我能够添加客户端凭据流。

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

我从appsettings.json上删除了这个

代码语言:javascript
复制
"Clients": {
  "WebApplication4.Client": {
    "Profile": "IdentityServerSPA"
  }
}

编辑Startup.csProgram.cs

代码语言:javascript
复制
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"}
        });
    });

这一请求将适用于:

代码语言:javascript
复制
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"},当然还要修改请求。

然后,服务器以以下方式进行响应:

代码语言:javascript
复制
{
    "error": "invalid_scope"
}

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

代码语言:javascript
复制
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"
      }

我带走的是:

代码语言:javascript
复制
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/

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

代码语言:javascript
复制
public static class Config
{
    public static IEnumerable<ApiScope> ApiScopes =>
        new List<ApiScope>
        {
        new ApiScope("WebApplication4.IntegrationAPI", "Integration API")
        };
}

代码语言:javascript
复制
services.AddIdentityServer()
    .AddInMemoryApiScopes(Config.ApiScopes)
    .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options =>...

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

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

代码语言:javascript
复制
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中删除旧客户端并使用以下代码:

代码语言:javascript
复制
services.AddIdentityServer()
    .AddInMemoryApiScopes(Config.ApiScopes)
    .AddInMemoryClients(Config.Clients)
    .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options => ...

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

代码语言:javascript
复制
{
    "error": "invalid_client"
}

日志:

代码语言:javascript
复制
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

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

代码语言:javascript
复制
services.AddAuthorization(options =>
{
    options.AddPolicy("IntegrationApiScope", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireClaim("scope", "WebApplication4.IntegrationAPI");
    });
});

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-13 09:10:04

这将起作用:

代码语言:javascript
复制
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并使用它获取一个令牌。

使用以下代码:

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73812921

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档