alex
alex

Reputation: 7463

Programmatically establish boto3 sessions with AWS SSO

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?

Upvotes: 2

Views: 10161

Answers (4)

aelgn
aelgn

Reputation: 900

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

Upvotes: 5

2ps
2ps

Reputation: 15956

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

Upvotes: 0

Peter Grape
Peter Grape

Reputation: 48

Here is a link to a Gist I found that will assist you halfway anyway, Still it will open a webbrowser but depending on the login process of your auth provider you should be able to cram your way through a webbrowser call using python requests lib.

https://gist.github.com/jcalvento/92861eb7ebda3fa064f3fbbb71acba41

Upvotes: 0

Coin Graham
Coin Graham

Reputation: 1584

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.

Upvotes: 2

Related Questions