Programmatically establish boto3 sessions with AWS SSO

Viewed 2478

I'm trying to establish a boto3 session with boto3.session.Session(profile_name='foo') but getting an UnauthorizedSSOTokenError error:

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.

I tried logging in with subprocess.run("aws sso login --profile foo"), but this opens up my web browser and prompts for manual confirmation.

Is there any way to programmatically establish boto3 sessions if you're using AWS SSO?

In other words, is there any way to avoid manual confirmation?

4 Answers

With just boto3, no. As you discovered already, you'll want to engaged the CLI for a solution with AWS SSO.

You can follow the steps here to setup the AWS CLI with AWS SSO. This will open a browser for you to manually confirm. My recommendation is that you increase the SSO session duration to be 12 hours. Effectively you sign in once a day and you're good for the rest of the day. This is the best mix of security and convenience. Other solutions like creating IAM roles, or totally automating the login are not recommended.

I wanted to handle SSO reauthentication on expiration automatically in my script and can live with a browser window being opened and (possibly) prompting the user to authorize device access.

Ended up with:

def establishSession(retry = True):
    session = boto3.Session(profile_name=AWS_PROFILE)
    sts = session.client('sts')
    try:
        identity = sts.get_caller_identity()
        print(f"Authorized as {identity['UserId']}")
        return session
    except botocore.exceptions.UnauthorizedSSOTokenError:
        if retry:
            subprocess.run(['aws','sso', 'login', '--profile', AWS_PROFILE])
            return establishSession(False)
        else:
            raise

The get_caller_identity api call is fast and does not need any special permissions. https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sts.html#STS.Client.get_caller_identity

@coin graham's answer is now out of date. Please refer to this example for how to establish an sso session via boto3.

Related