How to get profile data using AWS Cognito with Boto3 and OAuth? - amazon-web-services

Okay, so after a user logs in, I want to get their profile data. So the way I tried doing that was via boto3.client('cognito-idp').get_user but it keeps returning:
NotAuthorizedException: An error occurred (NotAuthorizedException) when calling the GetUser operation: Access Token does not have required scopes
To my knowledge, I have put every single built in Cognito scope and I am unsure why it is not working. Any help would be appreciated!
My Auth Script
scope = request.args.get(
'scope',
'email phone profile openid')
sumukey = make_session(scope=scope.split(' '))
authorization_url, state = sumukey.authorization_url(AUTHORIZATION_BASE_URL)
session['oauth2_state'] = state
return redirect(authorization_url)
My Return
sumukey = make_session(state=session.get('oauth2_state'))
token = sumukey.fetch_token(
TOKEN_URL,
client_secret=OAUTH2_CLIENT_SECRET,
authorization_response=request.url)
session['oauth2_token'] = token
return redirect(url_for('.index'))
Current Attempt to get data
client = boto3.client('cognito-idp')
response = client.get_user(
AccessToken=session['oauth2_token']['access_token']
)
return str(jsonify(response))
make_session
return OAuth2Session(
scope=scope,
client_id=OAUTH2_CLIENT_ID,
token=token,
state=state,
redirect_uri=OAUTH2_REDIRECT_URI,
auto_refresh_kwargs={
'client_id': OAUTH2_CLIENT_ID,
'client_secret': OAUTH2_CLIENT_SECRET,
},
auto_refresh_url=TOKEN_URL,
token_updater=token_updater)

Related

Invoking PowerBi rest api and generate token

I want to invoke PowerBI rest api calls to upload pbix files from local/specific repository.
How should I generate bearer token for authorization from Postman?
Will this rest api call work to generateToken?
What needs to passed as authorization token for this rest call?
Does myorg is the PowerBI account name? from where can I fetch the myorg value?
POST https://api.powerbi.com/v1.0/myorg/GenerateToken
Below are few more calls that I want to invoke through postman:
GET https://api.powerbi.com/v1.0/myorg/imports
GET https://api.powerbi.com/v1.0/myorg/reports/{reportId}
and few post calls also.
What will be a quick solution for generating token?
You can use this function to request access
it is necessary to create the Client ID in azure
https://learn.microsoft.com/en-us/power-bi/developer/embedded/register-app?tabs=customers%2CAzure
application_id= 'None'
application_secret= 'None'
user_id= 'None'
user_password= 'None'
accessToken = None
requestHeaders = None
tokenExpiry = None
accessToken_AD = None
requestHeaders_AD = None
tokenExpiry_AD = None
def pbi_auth(application_id,application_secret,user_id,user_password):
global accessToken
global requestHeaders
global tokenExpiry
data = {
'grant_type': 'password',
'scope': 'openid',
'resource': "https://analysis.windows.net/powerbi/api",
'client_id': application_id,
'client_secret': application_secret,
'username': user_id,
'password': user_password
}
token = requests.post("https://login.microsoftonline.com/common/oauth2/token", data=data)
assert token.status_code == 200, "Fail to retrieve token: {}".format(token.text)
#print("Got access token: ")
#print(token.json())
accessToken = token.json()['access_token']
requestHeaders= {
'Content-Type': 'application/json; charset=utf-8',
'Authorization': "Bearer {}".format(accessToken)
}
pbi_auth(application_id,application_secret,user_id,user_password)
reportId= ""
URI = "https://api.powerbi.com/v1.0/myorg/reports/{}".format(reportId)
queryResults = requests.get(URI, headers=requestHeaders)

Django Session Variables Don't Work In Stripe Webhook?

I am trying to use data saved in django session variables to run a function once the webhook has confirmed that 'checkout.session.completed' but I always get a key error. I am 100% sure the keys exist in the session variables.
Here is my webhook:
#csrf_exempt
def stripe_webhook(request):
# You can find your endpoint's secret in your webhook settings
endpoint_secret = 'secret'
payload = request.body
sig_header = request.META['HTTP_STRIPE_SIGNATURE']
event = None
try:
event = stripe.Webhook.construct_event(
payload, sig_header, endpoint_secret
)
except ValueError as e:
# Invalid payload
return HttpResponse(status=400)
except stripe.error.SignatureVerificationError as e:
# Invalid signature
return HttpResponse(status=400)
# Handle the checkout.session.completed event
if event['type'] == 'checkout.session.completed':
session = event['data']['object']
fulfull_order(session)
return HttpResponse(status=200)
Here is my fulfill order function:
def fulfull_order(session):
generator = PlanMaker(goal=request.session['goal'], gender=request.session['gender'])
/// send email code.
This line generator = PlanMaker(goal=request.session['goal'], gender=request.session['gender'])
Always gives a key error on request.session['goal'] The key definitely exists, it just seems it is inaccessible from the webhook view.
How to solve?
You should save the information you want to the metadata field when creating the checkout.Session.
def checkout(request):
session = stripe.checkout.Session.create(
payment_method_types=['card'],
line_items=[{
'price': 'price_key',
'quantity': 1,
}],
mode='payment',
success_url=request.build_absolute_uri(reverse('success_url')) + '?session_id={CHECKOUT_SESSION_ID}',
cancel_url=request.build_absolute_uri(reverse('cancel_url')),
metadata={'someKeyHere': 'your session variable data'}
)
return JsonResponse({
'session_id' : session.id,
'stripe_public_key' : settings.STRIPE_PUBLISHABLE_KEY
})
then you can access the information like session['metadata']['someKeyHere']
The webhook event is a separate request coming directly from Stripe that would not be related to any Django session and so this lack of session data would seem expected. As #Anthony suggests you can store this information in the Checkout Session metadata when you create the session. The metadata will be included in the webhook object.

Unauthorized Error with 500px OAuth api

I am trying to authorize in 500px.com with python-500px lib. So, the 500px.com has I standard Oauth system.
First of all we should generate the token from our key, secret params.
Python-500px makes it well and give us a correct url for asking response token and verifier
def smm500px (request):
CONSUMER_KEY = 'somekey'
CONSUMER_SECRET= 'somesecret'
handler = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
return redirect(handler.get_authorization_url())
After that it correctly redirect us to 500px auth when we can confirm installing our app
In third step the 500px.com redirect us to our complete auth url which was set in our 500px app. We receive aouth_token and verifier but something goes wrong in this step
def smm500px_complete(request):
oauth_token = request.GET.get('oauth_token', '')
oauth_verifier = request.GET.get('oauth_verifier', '')
CONSUMER_KEY = 'somekey'
CONSUMER_SECRET= 'somesecret'
handler = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
handler.set_request_token(str(oauth_token), str(oauth_verifier))
#token = handler.get_access_token(str(oauth_verifier))
token = handler.get_xauth_access_token('reflexsmm','innovateordie')
logger.debug('key: %s' % token.key)
logger.debug('secret: %s' % token.secret)
return HttpResponse(token.key)
If I delete the str() function in any method I have another mistake with incorrect character mapping (character mapping must return integer, None or unicode)
I don't have any idea what to do.

Getting OAuth access token in Explara API

I'm trying to get an access token for explara API using an Django application using the following code. It's working fine for getting code. After getting code when it goes to else part of get_explara_token view; give the error '{"error":"invalid_request","error_description":"The grant type was not specified in the request"}' while I has defined grant type as authorization_code as mentioned in Explara API documentation here http://developers.explara.com/get-api-access
views.py
import requests
import urllib
def get_explara_token(request):
access_code = request.GET.get('code')
if access_code is None:
code = 'code'
state = 'event'
query = {
'response_type':code,
'client_id': EXPLARA_CLIENT_ID,
'state':state
}
url = 'https://account.explara.com/account/oauth/authorize?%s' % urllib.urlencode(query)
return HttpResponseRedirect(url)
else:
url = 'https://account.explara.com/account/oauth/token/' + 'client_id=' + str(EXPLARA_CLIENT_ID) + '&client_secret=' + str(EXPLARA_CLIENT_SECRET) + '&grant_type=' + 'authorization_code' + '&code=' + str(access_code)
response = requests.post(url)
return HttpResponse(response)
What am I doing wrong?
You should post data in that way:
requests.post('https://account.explara.com/account/oauth/token', data={'grant_type': 'authorization_code', 'client_id': 123123123, 'client_secret': '123123123', 'code': '123123'}).content
Instead of that you tried to pass data via GET parameters.

KeyError: access token

I have already test this before and it's work. Now the error back again and I didn't do any changes on my social app.
Here are my codes:
def get_profile(request, token=None):
args = {
'client_id': settings.FACEBOOK_APP_ID,
'client_secret': settings.FACEBOOK_APP_SECRET,
'redirect_uri': request.build_absolute_uri(reverse('social:fb_callback')),
'code': token,
}
target = urllib.urlopen('https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read()
response = cgi.parse_qs(target)
access_token = response['access_token'][-1]
return access_token
Obviously, your request is not successful and the response doesn't have an access token. According to facebook docs, when a request isn't good, it returns a response with an error element, something like:
{
error: {
message: "Missing redirect_uri parameter.",
type: "OAuthException",
code: 191
}
}
So, in your function, you should do something like:
class FacebookAccessException(Exception): pass
def get_profile(request, token=None):
...
response = json.loads(urllib_response)
if 'error' in response:
raise FacebookAccessException(response['error']['message'])
access_token = response['access_token'][-1]
return access_token
PS:
Try to use better urllib. You should try Requests.