KeyError: access token - django

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.

Related

Google cloud reCAPTCHA Enterprise showing invalid argument error

devs.
I am migrating my Recaptcha V2 to the Recaptcha enterprise using the below link.
https://cloud.google.com/recaptcha-enterprise/docs/using-features
the frontend integration part work and the Recaptcha checkbox part are showing.
On the backend side after the user submit the form passing the Recaptcha test. to verify the Recaptcha test, I call google REST API to create an assessment.
I am using this link.
https://cloud.google.com/recaptcha-enterprise/docs/create-assessment#rest-api
code of the function to verify user response.
def verify_captcha_response(self, recaptcha_response):
"""
Verify the Google Recaptcha V2 response of the request
- if recatacha response value is more than the value set
on google recaptcha admin.
- if request fail error will be raise and no response will be accept
"""
if not recaptcha_response:
return False
if isinstance(recaptcha_response, list):
recaptcha_response = recaptcha_response[0]
url = "https://recaptchaenterprise.googleapis.com/v1/projects/%s/assessments?key=%s" % ("Project id", settings.RECAPTCHA_SITE_KEY)
recaptcha_secret_key = settings.RECAPTCHA_SECRET_KEY,
headers={'Content-Type': 'application/json'}
data = {
"event":{
"token": recaptcha_response,
"siteKey": recaptcha_secret_key,
"expectedAction": "login"
}
}
response = requests.post(url, headers=headers,
data=data)
result = response.json()
if not result['success']:
if 'timeout-or-duplicate' in result['error-codes']:
raise forms.ValidationError(msg.RECAPTCHA_FAILED)
return False
return True
The response I am getting.
{
"error": {
"code": 400,
"message": "Request contains an invalid argument.",
"status": "INVALID_ARGUMENT"
}
}
but as per the documentation, I am passing all the arguments.
Thank you.

getting code 400 message Bad request syntax , after post from flutter

getting code 400 message Bad request syntax , after post from flutter,
with postman request send and no problem but with flutter after Post Map data to Django server i get this error
[19/May/2020 14:58:13] "POST /account/login/ HTTP/1.1" 406 42
[19/May/2020 14:58:13] code 400, message Bad request syntax ('32')
[19/May/2020 14:58:13] "32" 400 -
Django
#api_view(['POST'])
def login_user(request):
print(request.data)
if request.method == 'POST':
response = request.data
username = response.get('username')
password = response.get('password')
if password is not None and username is not None:
user = authenticate(username=username, password=password)
if user is not None:
create_or_update_token = Token.objects.update_or_create(user=user)
user_token = Token.objects.get(user=user)
return Response({'type': True, 'token': user_token.key, 'username': user.username},
status=status.HTTP_200_OK)
else:
return Response({'type': False, 'message': 'User Or Password Incorrect'},
status=status.HTTP_404_NOT_FOUND)
else:
return Response({'type': False, 'message': 'wrong parameter'}, status=status.HTTP_406_NOT_ACCEPTABLE)
else:
return Response({'type': False, 'message': 'method is wrong'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)
flutter
Future<dynamic> postGoa(String endpoint, Map data)async{
Map map = {
"username":"user",
"password":"password"
};
var url = _getUrl("POST", endpoint);
var client = new HttpClient();
HttpClientRequest request = await client.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.headers.set('Authorization', 'Bearer '+ athenticated
);
request.add(utf8.encode(json.encode(map)));
HttpClientResponse response = await request.close();
String mydata= await response.transform(utf8.decoder).join();
client.close();
return mydata;
}
}
after add
request.add(utf8.encode(json.encode(map)));
i get error in Django console
Try printing out your request headers from the Django application.
print(request.headers)
I bet one of the headers is Content-Type: ''. If that is the case, Django isn't reading your POST data because it thinks there is no data. I recommend calculating the length of the content you are sending in Flutter, then sending the correct Content-Length header with your request.
That might look something like this (in your Flutter app):
encodedData = jsonEncode(data); // jsonEncode is part of the dart:convert package
request.headers.add(HttpHeaders.contentLengthHeader, encodedData.length);

How to get profile data using AWS Cognito with Boto3 and OAuth?

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)

migrate from urllib2 to requests python 2.7

I am trying to take some working code and change from urlib2 to requests.
The original code provides basic login information of username, password and posts the KEY and SECRET in the header of the urllib2 request. The following code is my attempt to change to using the requests module and gain some functionality for making additional API calls. I have tried dozens of combinations and all return a code 400. Apparently, my requests code does not successfully furnish the needed information to return a 200 response and provide the needed authorization token.
## Import needed modules
import urllib2, urllib, base64
import httplib
import requests
import json
## initialize variables
KEY = "7f1xxxx-3xxx-4xxx-9a7f-8be66839dede"
SECRET = "45xxxxxx-45xxx-469a-9ae9-a7927a76cfeb"
userName = "my-email#xxx.com"
passWord = "mypassword"
URL = "https://company.com/auth/token"
token = None
sessionid = None
DATA = urllib.urlencode({"grant_type":"password",
"username":userName,
"password":passWord})
base64string = base64.encodestring('%s:%s' % (KEY, SECRET)).replace('\n', '')
request = urllib2.Request(URL, DATA)
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)
token = result.read()
print token
This returns my authorization token and all is well. I can pass the token to the authorization server and have full access to the api for interacting with the database. Below is the attempt to use requests and have the added functions it provides.
client = requests.session()
payload = {"grant_type":"password",
"username":userName,
"password":passWord,
"applicationId": KEY
}
headers = {'content-type':'application/json',
"grant_type":"password",
"username":userName,
"password":passWord,
'applicationsId': KEY,
'Authorization': base64string,
'token': token,
'sessionid': sessionid
}
response = client.post(URL, params = payload, headers=headers)
token = response.content
print token
{"error":"invalid_request"}
print response
<Response [400]>
If you want to use basic auth you should use the method from requests..
Your post should look like
response = client.post(
URL,
params = payload,
headers=headers,
auth=HTTPBasicAuth(
KEY,
SECRET
))
Somewhere in a post a contributor to another question mentioned some items actually needed to be in the body of the request not in the header. I tried various combos and the following solved the 400 response and accomplished my goals.
data = {"grant_type":"password",
"username":userName,
"password":passWord,
"applicationId": KEY
}
headers = {'Authorization': "Basic %s" % base64string,
'token': token
}
response = client.post(URL, data = data, headers=headers)
token = response.text
print token

Instagram Invalid Response Error - 400

I have the following code.
params = {'client_id':settings.SOCIAL_AUTH_INSTAGRAM_KEY,
'client_secret':settings.SOCIAL_AUTH_INSTAGRAM_SECRET,
'aspect':'media',
'object':'tag',
'object_id':instance.hashtag,
'callback_url':
'http://subdomain.domain.net:8000/campaigns/hook'}
response = requests.post('https://api.instagram.com/v1/subscriptions',
data=params)
And I get response
'{"meta":{"error_type":"APISubscriptionError","code":400,"error_message":"Invalid
response"}}'
My domain is reachable from outside. Any ideas?
This was because Instagram sends a GET request to my callback_url
and wants me to response with hub.challenge parameter like below
if self.request.GET:
response = request.GET.get('hub.challenge')
return HttpResponse(response)