AWS Boto3 sts get_caller_identity - 如果凭据无效则捕获异常

问题描述 投票:0回答:1

使用 Python 应用程序,使用 Boto3 v1.26.59(和相同版本的 botocore)所做的第一件事是尝试获取用户的用户名。我们有身份中心 (SSO) 用户。使用陈旧的凭据(令牌),抛出两个异常,我似乎无法捕捉到它们。这是一个片段:

import boto3  # type: ignore
import botocore.errorfactory as ef
import botocore.exceptions as bcexp


def profile_user_name(profile_name: str) -> Optional[str]:
    session = boto3.Session(profile_name=profile_name)
    sts = session.client("sts")
    try:
        user_id = sts.get_caller_identity().get("UserId")
        return user_id.split(":")[-1].split("@")[0]
    except ef.UnauthorizedException as e:
        _logger.error(f'Not authenticated. Please execute:  aws sso login --profile {profile_name}')
        return None
    except bcexp.UnauthorizedSSOTokenError as e:
        _logger.error(f'Not authenticated. Please execute:  aws sso login --profile {profile_name}')
        return None
    except Exception as e:
        _logger.error(f"Encountered exception '{str(e)}'!")
        return None

上面代码抛出的异常如下所示:

Refreshing temporary credentials failed during mandatory refresh period.
Traceback (most recent call last):
  File "/Users/kevinbuchs/lib/python3.11/site-packages/botocore/credentials.py", line 2121, in _get_credentials
    response = client.get_role_credentials(**kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/kevinbuchs/lib/python3.11/site-packages/botocore/client.py", line 530, in _api_call
    return self._make_api_call(operation_name, kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/kevinbuchs/lib/python3.11/site-packages/botocore/client.py", line 960, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.errorfactory.UnauthorizedException: An error occurred (UnauthorizedException) when calling the GetRoleCredentials operation: Session token not found or invalid

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/kevinbuchs/lib/python3.11/site-packages/botocore/credentials.py", line 510, in _protected_refresh
    metadata = self._refresh_using()
               ^^^^^^^^^^^^^^^^^^^^^
  File "/Users/kevinbuchs/lib/python3.11/site-packages/botocore/credentials.py", line 657, in fetch_credentials
    return self._get_cached_credentials()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/kevinbuchs/lib/python3.11/site-packages/botocore/credentials.py", line 667, in _get_cached_credentials
    response = self._get_credentials()
               ^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/kevinbuchs/lib/python3.11/site-packages/botocore/credentials.py", line 2123, in _get_credentials
    raise UnauthorizedSSOTokenError()
botocore.exceptions.UnauthorizedSSOTokenError: The SSO session associated with this profile has expired or is otherwise invalid. To refresh this SSO session run aws sso login with the corresponding profile.
Encountered exception 'The SSO session associated with this profile has expired or is otherwise invalid. To refresh this SSO session run aws sso login with the corresponding profile.'!
The auth profile 'dev-devaccess-default' is not logged in. Login with 'aws sso login --profile dev-devaccess-default' and retry!

我想我会在提交 GitHub 问题之前检查我是否遗漏了一些技巧。

python amazon-web-services single-sign-on boto botocore
1个回答
0
投票

你的问题一直困扰着我,所以我在周末设置了一些东西。这对我有用。

from botocore.exceptions import ClientError

def profile_user_name(profile_name: str):
    session = boto3.Session(profile_name=profile_name)
    sts = session.client("sts")
    try:
        user_id = sts.get_caller_identity().get("UserId")
        print(user_id.split(":")[-1].split("@")[0])
    except bcexp.UnauthorizedSSOTokenError as e:
        _logger.error(f'Not authenticated. Please execute:  aws sso login --profile {profile_name}')
        return None
    except ClientError as e:
        if e.response['Error']['Code'] == "ExpiredToken":
            _logger.error(f'Not authenticated. Please execute:  aws sso login --profile {profile_name}')
            return None
        print("Caught generic exception")
        return None

© www.soinside.com 2019 - 2024. All rights reserved.