根据最新的boto3版本于2023年10月23日更新(感谢评论者@Adam Smith的指导,他的无形之手引导我们更新了在较新版本的boto3中提取角色凭证的方法):
下面是经过测试的冗长而复杂的答案,适用于boto3==1.28.69:
这是一个八步骤的过程,其中:
- 使用
sso-oidc.register_client
注册客户端
- 使用
sso-oidc.start_device_authorization
启动设备授权流程
- 使用
webbrowser.open
将用户重定向到SSO登录页面
- 轮询
sso-oidc.create_token
直到用户完成登录
- 使用
sso.list_account_roles
列出并向用户展示账户角色
- 使用
sso.get_role_credentials
获取角色凭证
- 使用(6)中的会话凭证创建一个新的boto3会话
- 吃一个饼干
第8步非常关键,作为任何成功的授权流程的一部分,不应被忽视。
在下面的示例中,
account_id
应该是您要获取凭证的账户的账户ID。而
start_url
应该是AWS为您生成的用于启动SSO流程的URL(在AWS SSO管理控制台的设置下)。
from time import time, sleep
import webbrowser
from boto3.session import Session
session = Session()
account_id = '1234567890'
start_url = 'https://d-0987654321.awsapps.com/start'
region = 'us-east-1'
sso_oidc = session.client('sso-oidc')
client_creds = sso_oidc.register_client(
clientName='myapp',
clientType='public',
)
device_authorization = sso_oidc.start_device_authorization(
clientId=client_creds['clientId'],
clientSecret=client_creds['clientSecret'],
startUrl=start_url,
)
url = device_authorization['verificationUriComplete']
device_code = device_authorization['deviceCode']
expires_in = device_authorization['expiresIn']
interval = device_authorization['interval']
webbrowser.open(url, autoraise=True)
for n in range(1, expires_in // interval + 1):
sleep(interval)
try:
token = sso_oidc.create_token(
grantType='urn:ietf:params:oauth:grant-type:device_code',
deviceCode=device_code,
clientId=client_creds['clientId'],
clientSecret=client_creds['clientSecret'],
)
break
except sso_oidc.exceptions.AuthorizationPendingException:
pass
access_token = token['accessToken']
sso = session.client('sso')
account_roles = sso.list_account_roles(
accessToken=access_token,
accountId=account_id,
)
roles = account_roles['roleList']
role = roles[0]
role_creds = sso.get_role_credentials(
roleName=role['roleName'],
accountId=account_id,
accessToken=access_token,
)['roleCredentials']
session = Session(
region_name=region,
aws_access_key_id=role_creds['accessKeyId'],
aws_secret_access_key=role_creds['secretAccessKey'],
aws_session_token=role_creds['sessionToken'],
)
sso
文件里有什么?如果你想这样做,你可以使用AWS_SHARED_CREDENTIALS_FILE环境变量指定凭证文件的新位置。 - Marcinsso
不是一个文件,而是一个目录。我正在更新工单。 - user1015214clientId
、clientSecret
和accessToken
是临时的 AWS 凭证吗?如果是,那么我认为您需要手动在 boto3 中加载它,并使用这些凭证创建新的 session。 - Marcin