使用 Amazon 开发工具包为联合用户构建具有 Amazon STS 的 URL - Amazon Identity and Access Management
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

使用 Amazon 开发工具包为联合用户构建具有 Amazon STS 的 URL

以下代码示例展示了如何:

  • 创建一个 IAM 角色,该角色授予对当前账户的 Amazon S3 资源的只读访问权限。

  • 从 Amazon 联合身份验证端点获取安全令牌。

  • 构建一个可以用于通过联合凭证访问控制台的 URL。

Python
SDK for Python(Boto3)
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

创建一个角色,该角色授予对当前账户的 S3 资源的只读访问权限。

def setup(iam_resource): """ Creates a role that can be assumed by the current user. Attaches a policy that allows only Amazon S3 read-only access. :param iam_resource: A Boto3 AWS Identity and Access Management (IAM) instance that has the permission to create a role. :return: The newly created role. """ role = iam_resource.create_role( RoleName=unique_name("role"), AssumeRolePolicyDocument=json.dumps( { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": {"AWS": iam_resource.CurrentUser().arn}, "Action": "sts:AssumeRole", } ], } ), ) role.attach_policy(PolicyArn="arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess") print(f"Created role {role.name}.") print("Give AWS time to propagate these new resources and connections.", end="") progress_bar(10) return role

从 Amazon 联合身份验证端点获取安全令牌并构建一个可用于通过联合凭证访问控制台的 URL。

def construct_federated_url(assume_role_arn, session_name, issuer, sts_client): """ Constructs a URL that gives federated users direct access to the AWS Management Console. 1. Acquires temporary credentials from AWS Security Token Service (AWS STS) that can be used to assume a role with limited permissions. 2. Uses the temporary credentials to request a sign-in token from the AWS federation endpoint. 3. Builds a URL that can be used in a browser to navigate to the AWS federation endpoint, includes the sign-in token for authentication, and redirects to the AWS Management Console with permissions defined by the role that was specified in step 1. :param assume_role_arn: The role that specifies the permissions that are granted. The current user must have permission to assume the role. :param session_name: The name for the STS session. :param issuer: The organization that issues the URL. :param sts_client: A Boto3 STS instance that can assume the role. :return: The federated URL. """ response = sts_client.assume_role( RoleArn=assume_role_arn, RoleSessionName=session_name ) temp_credentials = response["Credentials"] print(f"Assumed role {assume_role_arn} and got temporary credentials.") session_data = { "sessionId": temp_credentials["AccessKeyId"], "sessionKey": temp_credentials["SecretAccessKey"], "sessionToken": temp_credentials["SessionToken"], } aws_federated_signin_endpoint = "https://signin.aws.amazon.com/federation" # Make a request to the AWS federation endpoint to get a sign-in token. # The requests.get function URL-encodes the parameters and builds the query string # before making the request. response = requests.get( aws_federated_signin_endpoint, params={ "Action": "getSigninToken", "SessionDuration": str(datetime.timedelta(hours=12).seconds), "Session": json.dumps(session_data), }, ) signin_token = json.loads(response.text) print(f"Got a sign-in token from the AWS sign-in federation endpoint.") # Make a federated URL that can be used to sign into the AWS Management Console. query_string = urllib.parse.urlencode( { "Action": "login", "Issuer": issuer, "Destination": "https://console.aws.amazon.com/", "SigninToken": signin_token["SigninToken"], } ) federated_url = f"{aws_federated_signin_endpoint}?{query_string}" return federated_url

销毁为演示创建的资源。

def teardown(role): """ Removes all resources created during setup. :param role: The demo role. """ for attached in role.attached_policies.all(): role.detach_policy(PolicyArn=attached.arn) print(f"Detached {attached.policy_name}.") role.delete() print(f"Deleted {role.name}.")

使用之前定义的函数运行此方案。

def usage_demo(): """Drives the demonstration.""" print("-" * 88) print(f"Welcome to the AWS Security Token Service federated URL demo.") print("-" * 88) iam_resource = boto3.resource("iam") role = setup(iam_resource) sts_client = boto3.client("sts") try: federated_url = construct_federated_url( role.arn, "AssumeRoleDemoSession", "example.org", sts_client ) print( "Constructed a federated URL that can be used to connect to the " "AWS Management Console with role-defined permissions:" ) print("-" * 88) print(federated_url) print("-" * 88) _ = input( "Copy and paste the above URL into a browser to open the AWS " "Management Console with limited permissions. When done, press " "Enter to clean up and complete this demo." ) finally: teardown(role) print("Thanks for watching!")
  • 有关 API 详细信息,请参阅《Amazon SDK for Python(Boto3)API 参考》中的 AssumeRole

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将 IAM 与 Amazon 开发工具包配合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。