如何通过 cli 或 sdk 设置 Cognito 用户池应用程序客户端允许的自定义范围?

How can I set the allowed custom scopes of a Cognito User Pool App Client via cli or sdk?

TL;DR:有没有办法通过 cli 或 sdk 设置应用程序客户端自定义范围?

我正在尝试使用 CloudFormation 自动化我的 Cognito 部署。我已经制作了一些自定义资源,因为并非所有内容都受支持。为此,我使用 AWS JS SDK。我想为特定用户池中的应用程序客户端设置 'Allowed Custom Scopes'。但是,我无法在 AWS 提供的任何文档中找到如何执行此操作。 CLI 文档在此处 Cognito-user-identity docs 的文档中仅说明了这一点:

AllowedOAuthScopes
A list of allowed OAuth scopes. Currently supported values are "phone", "email", "openid", and "Cognito".

提到的范围是用户池中始终可用的默认范围。但我也使用由我定义的自定义资源服务器提供的自定义范围。那些看起来像:resourceServer.com/scope。我找不到任何关于设置这些范围的文档。

那么,有没有办法通过 cli 或 sdk 设置自定义范围?

AllowedOAuthScopes 字段支持自定义范围。

文档:https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html#CognitoUserPools-CreateUserPoolClient-request-AllowedOAuthScopes

通过 CLI 更新用户池客户端:https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/update-user-pool-client.html (查看 --allowed-o-auth-scopes 选项)

请参阅下面的示例 cloudformation

UserPoolResourceServer:
    Type: AWS::Cognito::UserPoolResourceServer
    Properties: 
        Identifier: users
        Name: User API
        UserPoolId: !Ref UserPool
        Scopes: 
            - ScopeName: "write"
              ScopeDescription: "Write access"
            - ScopeName: "read"
              ScopeDescription: "Read access"

UserPoolClientAdmin:
    Type: "AWS::Cognito::UserPoolClient"
    Properties:
        AllowedOAuthFlows: 
            - client_credentials
        AllowedOAuthFlowsUserPoolClient: true
        AllowedOAuthScopes: 
            - users/read
            - users/write

对于前来这里寻找解决方案的任何人,请遵循@JohnPauloRodriguez 的示例 。但是您可能需要在 UserPoolClient 模板中添加 DependsOn 属性键才能正常工作。

原因是,首先 Resource Server 这些自定义范围应该存在,然后我们才能在客户端中引用它们。根据 Cloud Formation Docs:

With the DependsOn attribute you can specify that the creation of a specific resource follows another. When you add a DependsOn attribute to a resource, that resource is created only after the creation of the resource specified in the DependsOn attribute.

因此 UserPoolClient 的模板将变为:

CognitoUserPoolClient:
    Type: AWS::Cognito::UserPoolClient
    DependsOn: UserPoolResourceServer
    Properties:
      UserPoolId: !Ref UserPool
      AllowedOAuthFlowsUserPoolClient: true
      AllowedOAuthFlows:
        - code
      AllowedOAuthScopes: 
        - users/read
        - users/write