Having been confused by AWS Congito for weeks… Are there any difference between access tokens retrieved by /oauth2/token
and boto3
? If so, how can my backend use an access token passed from my frontend? Is it the only way that importing aws-sdk
and aws-amplify
?
Or I have to change all my workflow?
My frontend initiate the authorization flow via the Cognito hosted UI and get the access token(lets call it oauth access token) by exchange the authorization code, then the access token is attached in header every time when my frontend request my backend:
// If code is present, exchange it for a token
const params = new URLSearchParams({
grant_type: 'authorization_code',
client_id: CLIENT_ID,
code: code, /* the authorization code */
redirect_uri: REDIRECT_URI,
});
try {
// Get token via aws api
const response = await fetch(`${DOMAIN}/oauth2/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: params,
});
My backend calls boto3.Session().client('cognito-idp').get_user()
with the oauth access token sent by frontend, to get user information:
def _getUser(token:str): # here the access token passed from frontend lies
# _cog_client is an instance of boto3.Session(...).client('cognito-idp')
return {
item["Name"]: item["Value"]
for item in _cog_client.get_user(AccessToken=token)["UserAttributes"]
}
and, EVERY SINGLE TIME the _getUser()
raises NotAuthorizedException
…
If the access token is retrieved by boto3.Session().client(‘cognito-idp’).initiate_auth()(let's call it **boto3 access token**),
get_user()` won’t raise error and it would function well:
def getAccessToken():
# for test purpose
resp=cog.initiate_auth(...) # cog is _cog_client, an instance of boto3.Session(...).client('cognito-idp')
return resp["AuthenticationResult"]["AccessToken"]
_getUser(getAccessToken()) # this works well!
If I do not use get_user()
but a GET call via, say, Requests
, it would work:
import requests as rq
ret=rq.get(
"https://test-influradar.auth.ap-southeast-1.amazoncognito.com/oauth2/userInfo",
headers={
'Authorization': f'Bearer {token}', # the oauth2 access token, NOT the boto3 access token
'Content-Type': 'application/json'
})
print(ret.json()) # 200 OK and expected response
So back to my question, are they really different and cannot be used in the other way(which means I would have to change either of my work flow), or my work flow itself is not good practice, i.e. the access token shouldn’t be fetched and pass(really?)?