{"message": "Invalid Form Body", "code": 50035} - python

Please help me with this, been searching for hours now. Here is a snippet of my code:
headers = {
'consent':'true',
'date_of_birth':'2000-08-05',
'email':email,
'password':password,
'username':username
}
response = req.post('https://discord.com/api/v9/auth/register', data=headers)
print(response.text)
email and password and username are correctly defined
it then returns me this error
{"message": "Invalid Form Body", "code": 50035}.
What can I do to fix this error?
I tried changing data to json and it came back with a different error. I want it to execute the api.

Here's an issue with this code snippet
The consent field seems to be missing in the payload of the post request, this field might be mandatory in discord API endpoint, so you should include it.
The data argument should not be used when passing headers to the requests.post() method. Instead, you should use the headers argument.
Here is the modified version of the code:
headers = {
'consent':'true',
'date_of_birth':'2000-08-05',
'email':email,
'password':password,
'username':username
}
response = req.post('https://discord.com/api/v9/auth/register', headers=headers)
print(response.text)
Please keep in mind that this code may work only if the endpoint accepts the payload you're providing in the headers, also keep in mind that this code is not handling the errors that might happen like network problems, invalid email/password, or other issues. You should add some error handling in the code to handle such cases.
Also, this will only work if you've implemented the logic for getting the email, password, username variables, you need to initialize the variables email, password, username with valid values before using them in the headers.
You might also need to check the discord API documentation to confirm the endpoint URL and its requirements to use the API endpoint.

Related

How to take take access tokens from oauth2

I'm having problems on taking the access token from the oauth2 platform with python.
Currently, that's what I'm using on my post request:
def token(self):
client_id=ID_DO_CLIENTE
client_secret=SECRET_TOKEN
grant_type='client_credentials'
response = requests.post("https://oauth2.googleapis.com/token",
auth=(client_id, client_secret),
data={'grant_type':grant_type,'client_id':client_id,'client_secret':client_secret})
print(response.text)
This specific code is returning the following error:
{
"error": "unsupported_grant_type",
"error_description": "Invalid grant_type: "
}
But I don't think the problem is the grant_type, since I've tried everything I've found online to solve this.
Anyway, if there's any info missing, please let me know. Please help !
A valid request will also need these headers in order to send data in the correct format - I suspect JSON is sent by default, resulting in a malformed request:
Content-Type: application/x-www-form-url-encoded
Authorization: Basic [base 64 encoded client id and secret]
TECHNIQUES
Aim to use the curl tool to get the token first, to ensure the setup is right - as in this article.
Also aim to trace the request via an HTTP proxy tool to ensure that the wire message is being sent correctly.
These techniques will make you more productive when working with OAuth.
CODE
I had a search and this answer seems to use the correct code, though you may be able to send the Authorization header like this:
auth=HTTPBasicAuth('user', 'pass')
This is a sample code for reference:
data = {'grant_type': 'client_credentials'}
requests.post(token_url,
data=data,
auth=(client_id, client_secret))
In the provided sample code, the data part is being sent incorrectly viz:
data={'grant_type':grant_type,'client_id':client_id,'client_secret':client_secret}
I think it should be this:
data={'grant_type':grant_type}
Adding the sample code which I am testing to verify the token generation logic:
client_id = '<value>'
client_secret = '<value>'
# This is optional
scope = '<uri>'
#Token generation step
#If scope is not defined above then remove it from this call
data = {'grant_type': 'client_credentials','scope': scope}
access_token_response = requests.post(token_url, data=data, verify=False, allow_redirects=False, auth=(client_id, client_secret))
print (access_token_response.headers)
print (access_token_response.text)
tokens = json.loads(access_token_response.text)
print ("access token: " + tokens['access_token'])

Retrieve access token for Yahoo API using OAuth 2.0 and Python requests

I am trying to retrieve the access token for the Yahoo API, using the explicit grant flow as described in this document:
https://developer.yahoo.com/oauth2/guide/flows_authcode
Everything is fine until Step 4: Exchange authorization code for Access Token
I wrote the following python script to retrieve the code:
import urllib2
import requests
import json
url = 'https://api.login.yahoo.com/oauth2/get_token'
body = "grant_type=authorization_code&redirect_uri=oob&code=************"
headers = {
'Authorization': 'Basic **************',
'Content-Type': 'application/json'
}
r = requests.post(url, data=body, headers=headers)
print r
Note: I replaced sensitive data with "****"
Now, when I execute the script, I only get the "401" error message.
I am 100% sure that the login credentials are fine, so it seems to be related to the way I make the request. It's also the first time that I am using "requests" in python.
Would be great, if you could give me some feedback on the code, and if I am passing the header and body information correctly. I am especially unsure about the passing of the body. The documentation only states the following:
Sample Request Body: grant_type=authorization_code&redirect_uri=https%3A%2F%2Fwww.example.com&code=abcdef
Change your body variable to a dict, i.e.,
body = {
'grant_type': 'authorization_code',
'redirect_uri': 'oob',
'code': '************',
}
No other changes are needed. Hope it helps.
Tough the problem already solved. But may be other user can still get the same 401 error even if they use correct dict as me. The problem is that the code generated in step 2 in the link can be only use ONCE. And this will get the same 401 error. This took me some time to figure it out. Hope this helps others.

Linkedin API Error {"error_description":"the client is not authorized","error":"unauthorized_client"}

When I try to submit my form from python flask to linkedin I get the following exception: {"error_description":"the client is not authorized","error":"unauthorized_client"}
I've checked the code and everything should be working.
post = {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": os.environ["REDIRECT_URI"],
"client_id": os.environ["API_KEY"],
"client_secret": os.environ["API_SECRET"]
}
access = requests.post("https://www.linkedin.com/uas/oauth2/accessToken", data=post)
return access.text + str(post)
All of my environment variables appear to be correct. (I've checked multiple times) but I'm still getting the same error. I have already registered the app on linkedin as well and have been strictly following the documentation. Anybody know what I might be doing wrong?
The problem wasn't with the access codes but with the REDIRECT_URI. I had it previously encoded for the get request so that it'd be in the proper formula for that. However that format doesn't work the same for a POST request. Rather than https%3A%2F%2Fwww.example.com%2Flinkedin it needs to be formatted https://www.example.com/linkedin. This is because the request library will escape the parameters, and if it's already escaped it will become double-escaped.

Errors loading JSON with Flask and Angular

I've solved my issue, but I'd like to know what was going wrong so I can address it in the future. I'm having issues decoding incoming JSON for use in my Flask application.
The code that sends it in Angular:
$http.post("/login", JSON.stringify($scope.loginForm))
.success(function(data, status, headers, config) {
console.log(data);
})
.error(function(data, status, headers, config) {
console.log("Submitting form failed!");
});
Important to note that the request type is set to application/json earlier up, with
$http.defaults.headers.post["Content-Type"] = "application/json";
The code that receives it within Flask:
data = request.get_json()
email_address = data.get("email_address")
password = data.get("password")
Attempting to load it this way returns an error 400, but any other way leads to some very strange issues. For example:
return json.dumps(request.get_json())
Will log {"password": "password", "email_address": "email#email.com"} in the console, but attempting to do this:
data = request.get_json()
email_address = data.get("email_address")
password = data.get("password")
With no difference whatsoever between this and the first block of code except that I'm not forcing it, I receive the exception "ValueError: need more than 1 value to unpack". Which implies that there aren't two values to unpack.
HOWEVER, they both work individually. If I do the above request and omit either of the data.get() lines above, the other will work.
What about my setup causes my JSON object to disintegrate the first time it's accessed?
I got around this by using request.json instead of request.get_json() but as request.json is being deprecated it's fairly important I know how to solve this in the future. Any pointers would be appreciated!
You can omit JSON.stringify and pass object directly to $http.post() method because angular will serialize it to JSON automatically it formData is object. So I assume that JSON.stringify will force angular to send is as x-www-form-urlencoded instead of application/json media type.
See default transformations section: angular $http service documentation

Yggdrasil authentication with Python

I decided to try to make an automated login script for Minecraft. However, the new authentication API is stumping me. I can't find any mentions of the new functionality of the API on here. This is my code as it stands:
import requests
import json
data = json.dumps({"agent":{"name":"Minecraft","version":1},"username":"abcdef","password":"abcdef","clientToken":""})
headers = {'Content-Type': 'application/json'}
r = requests.post('https://authserver.mojang.com', data=data, headers=headers)
print (r.text)
Unfortunately, this returns:
{"error":"Method Not Allowed","errorMessage":"The method specified in the request is not allowed for the resource identified by the request URI"}
According to this resource on request format, this error means that I didn't correctly send a post request. However, I clearly declared requests.post(), so my first question is how am I incorrect, and what is the correct way to go about this?
My second question is, since I'm relatively new to Python and JSON, how would I replace the username and password fields with my own data, inside a variable?
You haven't specified an endpoint in your POST request, for example:
https://authserver.mojang.com/authenticate
The root of the website probably does not accept POST requests
http://wiki.vg/Authentication#Authenticate

Categories

Resources