如何使用 Amazon Cognito 身分集區來授予使用者對 AWS 服務的存取權?

2 分的閱讀內容
0

我想要使用 Amazon Cognito 使用者集區,讓使用者能夠存取 AWS 資源。

解決方案

您可以整合 Amazon Cognito 身分集區與 Amazon Cognito 使用者集區,以發出暫時憑證以存取 AWS 資源。藉由使用者集區來設定身分集區,以設定驗證提供者。透過使用者集區驗證使用者後,請使用具有驗證流程的使用者身分字符,從身分集區擷取暫時憑證。設置基本的身分驗證流程和增強的身分驗證流程,來擷取暫時憑證。

**重要事項:**在以下範例 AWS Command Line Interface (AWS CLI) 命令中,用您的值取代範例字串的所有執行個體。(例如,用您的身分集區 ID 取代 "example_identity_pool_id",或用您的 AWS 區域的身分 ID 取代 "abcdef"。)

基本流程

**注意:**如果您在執行 AWS Command Line Interface (AWS CLI) 命令時收到錯誤,請確保您使用的是最新的 AWS CLI 版本

執行下列步驟,以使用基本的 authflow 擷取暫時 AWS 憑證:

1.    從舊版 Amazon Cognito 主控台中,選擇 Manage Identity Pools (管理身分集區)。選取您要更新的 Amazon Cognito 身分集區的名稱,然後選擇 Edit identity pool (編輯身分集區)。在 Authentication flow settings (驗證流程設定) 下,選取 Allow Basic (Classic) Flow (允許基本 (典型) 流程),然後儲存變更。

2.    若要在身分集區中產生或擷取使用者身分,請呼叫 GetId API。

範例 get-id 命令:

aws cognito-identity get-id --identity-pool-id "example_identity_pool_id" --logins cognito-idp.example_region.amazonaws.com/example_cognito_user_pool_id=example_cognito_user_id_token

範例輸出:

{
    "IdentityId": "region:abcdef"
}

3.    若要擷取開放的 ID 字符,請使用步驟 2 中的結果呼叫 GetOpenIdToken API。

範例 get-open-id-token 命令:

aws cognito-identity get-open-id-token --identity-id "region:abcdef" --logins cognito-idp.example_region.amazonaws.com/example_user_pool_id=example_cognito_user_id_token

範例輸出:

{
    "IdentityId": "region:abcdef",
    "Token": "HIJKLMN"
}

4.    若要擷取驗證角色的暫時憑證,請使用步驟 3 中的字符來呼叫 AssumeRoleWithWebIdentity API。

範例 assume-role-with-web-identity 命令:

aws sts assume-role-with-web-identity --role-arn "example_auth_role_arn_of_the_identity_pool" --web-identity-token "HIJKLMN" --role-session-name "example_session_name"

範例輸出:

{
    "Credentials": {
        AccessKeyId": "xxxxxxxxxxxx",
        SecretAccessKey": "xxxxxxxxxxxx",
        SessionToken": "xxxxxxxxxxxx",
        Expiration": ""
    },
    "SubjectFromWebIdentityToken": "",
    "AssumedRoleUser": {
        "AssumedRoleId": "",
        "Arn": ""
    },
    "Provider": "cognito-identity.amazonaws.com",
    "Audience": ""
}

增強的流程

執行下列步驟,以使用增強的 authflow 擷取暫時 AWS 憑證:

1.    若要在 Amazon Cognito 身分集區中產生或擷取使用者身分,請呼叫 GetId API。

範例 get-id 命令:

aws cognito-identity get-id --identity-pool-id "example_identity_pool_id" --logins cognito-idp.example_region.amazonaws.com/example_cognito_user_pool_id=example_cognito_user_id_token

範例輸出:

{
    "IdentityId": "region:abcdef"
}

2.    若要從身分集區擷取暫時憑證,請呼叫 GetCredentialsForIdentity API。

範例 get-credentials-for-identity 命令:

aws cognito-identity get-credentials-for-identity --identity-id region:abcdef --logins cognito-idp.example_region.amazonaws.com/example_cognito_user_pool_id = example_cognito_user_id_token

範例輸出:

{
    "IdentityId": "region:abcdef",
    "Credentials": {
        "AccessKeyId": "xxxxxxxxxx",
        "SecretKey": "xxxxxxxxxx",
        "SessionToken": "xxxxxxxxxx",
        "Expiration": ""
    }
}

若要進一步了解複雜的以角色為基礎的存取控制和以屬性為基礎的存取控制,請參閱使用 Amazon Cognito 身分集區進行精細的存取控制


相關資訊

身分集區 (聯合身分) 驗證流程

AWS 官方
AWS 官方已更新 1 年前