我正在開發一個 python 應用程式,其目的是將資料上傳到 S3。由于它必須獨立安裝在不同的設備上,我不希望在每個平臺上都存盤 aws 憑證,但我想創建一種基于Amazon Cognito的身份驗證方法。
需要一種基于用戶名和密碼的登錄方法,因此用戶必須經過身份驗證才能被授權上傳檔案。我創建了一個用戶池和身份池,這是我想要遵循的模式:

這是我為驗證用戶而撰寫的代碼:
import os
import boto3
username = "user1997"
password = "abcd1234!!"
client = boto3.client("cognito-idp", region_name="ap-south-1")
response = client.initiate_auth(
ClientId=os.getenv("COGNITO_USER_CLIENT_ID"),
AuthFlow="USER_PASSWORD_AUTH",
AuthParameters={"USERNAME": username, "PASSWORD": password},
)
access_token = response["AuthenticationResult"]["AccessToken"]
但我不知道如何使用access_token從Identity Pool獲取臨時憑證。
uj5u.com熱心網友回復:
訪問令牌不是您想要的。您可以將身份令牌與 get_id 和 get_credentials_for_identity 呼叫結合使用,以最終獲取臨時 AWS 憑證。例如:
identityId = identity.get_id(
IdentityPoolId='us-east-1:xyxyxyxy-ab23-9989-7767-776x7676f5',
Logins={
'cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxxxx': id_tok
}
)['IdentityId']
aws_cred = identity.get_credentials_for_identity(
IdentityId=identityId,
Logins={
'cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxxxx': id_tok
}
)['Credentials']
aws_cred 將擁有訪問密鑰、秘密密鑰和會話令牌。您可以使用這些來簽署 AWS 呼叫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/403107.html
標籤:
