question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Invalid Security Token

See original GitHub issue

Invalid Security Token

Expected Behavior

boto3 cognito-idp should accept my session token created from root credentials from the root IAM user, (client insiatiend with boto3 sts) and perform the operations(admin_confirm_user,admin_update_user_attributes …, )

Current Behavior

boto3 cognito-idp client keeps complaing about and invalid security token, and when I try to boto3 sts client from cognito user credentials it complains its own security token is invalid because it does have any

Possible Solution

show us a way to assign roles and policies cognito user client or access the cognito user in the aws console

Steps to Reproduce

boto3_client_setup createAccount_admin_confirm_user_error end_user_flow

Environment

property value data
OS Microsoft Windows 10 Pro
Frontend Application Angular v 11.2.14
Backend Application Python v3.9.5
boto3 boto3==1.17.107, botocore==1.20.107,s3transfer==0.4.2

FILE requirements.txt

boto3==1.17.107
botocore==1.20.107
certifi==2021.5.30
chardet==4.0.0
idna==2.10
jmespath==0.10.0
lorem==0.1.1
Pillow==8.3.1
protobuf==3.17.3
PyJWT==2.1.0
python-dateutil==2.8.1
python-dotenv==0.18.0
requests==2.25.1
s3transfer==0.4.2
six==1.16.0
tornado==6.1
urllib3==1.26.6
watchdog==2.1.3

FILE auth_backend.py`

import sys
if sys.platform == "win32":
    sys.path.append(sys.path[0] + "\\site-packages\\windows")
elif sys.platform =="linux":
    sys.path.append(sys.path[0] + "/site-packages/linux")
import json
import os
import uuid
import datetime
import time
import pprint
import asyncio
import json
import datetime
# import pytz
import time
pp = pprint.PrettyPrinter(indent=4, compact=True, width=1)
import random
import lorem
import jwt
import requests
from datetime import datetime,timedelta
from operator import attrgetter,itemgetter


# aws cognito
import boto3
import hmac, hashlib, base64
app_client_id = os.getenv('COGNITO_USER_CLIENT_ID')
sec_key = os.environ.get("COGNITO_CLIENT_SECRET")
user_pool_id =os.environ.get("COGNITO_USER_POOL_ID")

#
sts_client_id =os.environ.get("ROOT_USER_CLIENT_ID")  || # STS_USER_CLIENT_ID
sts_client_secret =os.environ.get("ROOT_USER_CLIENT_SECRET") # STS_USER_CLIENT_SECRET
session_client = boto3.client(
    'sts',
    aws_access_key_id=    sts_client_id,
    aws_secret_access_key=sts_client_secret,
    region_name=os.getenv('COGNITO_REGION_NAME')
)
session_token = session_client.get_session_token().get("Credentials").get("SessionToken")

client = boto3.client(
    'cognito-idp',
    aws_access_key_id=     app_client_id,
    aws_secret_access_key= sec_key,
    aws_session_token=session_token,
    region_name=os.getenv('COGNITO_REGION_NAME')
)
#



# end

class my_ibm_language_client():

    def error_handler(self,e,env):
        print("---------------------------")
        print('my custom error at {}\n'.format(env))
        print(e.__class__.__name__)
        print(e)
        print("---------------------------")
        return {
            'status':500,
            'message': 'an error occured check the output from the backend'
        }

    def __init__(self):
        self.datetime = datetime
        self.timedelta = timedelta
        self.time = time
        self.uuid = uuid
        self.random = random
        self.requests = requests
        self.lorem  = lorem
        self.jwt = jwt

        # login from facebook user
        self.auth_enum = {
            "Error":"Log In Again",
            "Authorized":"Authorized",
            "Invalid":"Please try again",
        }
        #

        # aws cognito
        self.attrgetter = attrgetter # look up python destructuring
        self.itemgetter = itemgetter
        self.client = client
        self.sec_key = sec_key
        self.app_client_id = app_client_id
        self.user_pool_id = user_pool_id
        self.hmac = hmac
        self.hashlib = hashlib
        self.base64 = base64
        #

    def execute(self, data):

        #setup

        jwt = self.jwt
        timedelta = self.timedelta
        datetime = self.datetime
        time = self.time
        uuid = self.uuid
        random = self.random
        lorem = self.lorem
        requests = self.requests
        hmac = self.hmac
        hashlib = self.hashlib
        base64 = self.base64



        env = data.get("env")
        username = data.get("user")
        password = data.get("pass")
        result = data.get("result")
        token = data.get("token")
        target = data.get("target")
        access_token = data.get('access_token')

        # aws cognito
        client = self.client
        sec_key = self.sec_key
        app_client_id = self.app_client_id
        totp = data.get('totp')
        user_pool_id =self.user_pool_id
        #



        if(env == 'createAccount'):
            print('-------------------')
            print('\n{}\n'.format('createAccount'))
            try:
                message = bytes(username+app_client_id,'utf-8')
                key = bytes(sec_key,'utf-8')
                secret_hash = base64.b64encode(hmac.new(key, message, digestmod=hashlib.sha256).digest()).decode()


                # client sign up
                client.sign_up(
                    ClientId=app_client_id,
                    Username=username,
                    Password=password,
                    SecretHash=secret_hash
                )
                #

                # confirm sign up
                print("error occurs here")
                client.admin_confirm_sign_up(
                    UserPoolId=user_pool_id,
                    Username=username,
                )
                #

                # get access token
                response = client.initiate_auth(
                    ClientId=app_client_id,
                    AuthFlow='USER_PASSWORD_AUTH',
                    AuthParameters={
                        'USERNAME': username,
                        'PASSWORD': password,
                        'SECRET_HASH':secret_hash
                    },
                )
                access_token = response.get('AuthenticationResult').get('AccessToken')
                refresh_token = response.get('AuthenticationResult').get('RefreshToken')
                #

                #  verify their email
                # client.admin_update_user_attributes(
                #     UserPoolId=user_pool_id,
                #     Username=username,
                #     UserAttributes=[
                #         {
                #             'Name': "email_verified",
                #             'Value': "true"
                #         },
                #     ],
                # )
                client.update_user_attributes(
                    UserAttributes=[
                        {
                            'Name': "email_verified",
                            'Value': "true"
                        },
                    ],
                    AccessToken=access_token,
                )

                #



                # enable MFA
                response =client.admin_set_user_mfa_preference(
                    SoftwareTokenMfaSettings={
                        'Enabled': True,
                        'PreferredMfa': True
                    },
                    Username=username,
                    UserPoolId='us-east-2_Dr4tGpEJa'
                )
                pp.pprint(response)
                #





                return {
                    'status':200,
                    "refresh_token":refresh_token,
                    'message':{
                        "message":"OK",
                        "access_token":access_token,
                    }
                }
            # try:
            #     None
            except BaseException as e:
                return self.error_handler(e,env)


        return {
            "status" :500,
            "message": "Check the backend env dictionary you did set it so the backend didnt do anything"
        }

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
MichaelOdumosu57commented, Jul 16, 2021

You might not see this but I made a video on the issue here Check it out feel free to like share and subscribe https://www.youtube.com/watch?v=YuP4C5jaltY

1reaction
MichaelOdumosu57commented, Jul 13, 2021

Many thanks your hunch was correct whichever user has admin rights can access the user pool through the user-pool-id, the user with admin priviliges will be granted access.

Will follow with a youtube video on our youtube channel many thanks https://www.youtube.com/channel/UCmqEX_zasOf3AQ9vnPkxtjg

Read more comments on GitHub >

github_iconTop Results From Across the Web

What is this Invalid Security Token Error?
When trying to view the products contained within a category I am given the error: "Sorry, your request could not be processed as...
Read more >
"Invalid Security Token" error during Login - MATLAB Answers
When I login with my data, it says "Invalid Security Token" and there's only an option to close the program. Please help me...
Read more >
Topic Tag: Invalid Security Token - WordPress.org
Topic Tag: Invalid Security Token · [Wordfence Security - Firewall & Malware Scan] your browser sent an invalid security token. please try reloading...
Read more >
Device Showing Pending in NCM: Invalid Security Token
Device showing pending in NCM; Local admin page showing an error of "Invalid Security Token"; Initialized status over gray circle with three ...
Read more >
Salesforce Panel Error "invalid Security Token"
When initially setting up the Salesforce Switchboard Panel in Switchvox, some users may experience an error message "Invalid Security Token" when attempting to ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found