Why I am receiving 405 error for request? - python

I am trying to send a post request using python3.6 to oauth2 server to get my access token, it is showing response 405. Can someone tell me what I am doing wrong here
import requests
client_id = 'client_id'
client_secret = 'my client secret'
r = request.post('serverurl/oauth2/token&Content-Type="application/x-www-form-urlencoded"',data = {'grant_type':'authorization_code',
'code':'91a8a5e4-c5b3-4e2a-91ca-d59fe139526c',
'client_id':client_id,
'client_secret':client_secret,
'redirect_uri':'actualredirecturl'
}

I solved it using the following code
here is the code
import requests,base64
client_id = "myclientid"
client_secret = "myclientsecret"
redirect_uri = 'my redirect url'
code = 'code return by server on login'
requestHeaders = {
'Authorization': 'Basic ' + base64.b64encode(client_id + ':' + client_secret),
'Content-Type': 'application/x-www-form-urlencoded'
}
requestBody = {
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': redirect_uri
}
response = requests.post('token_url', data=requestBody, headers=requestHeaders)
token = response.json()['access_token']
Hope that helps

Related

Spotify web api call gives wrong code (python)

To get an authorization code from the Spotify web api I use this code:
AUTH_URL = 'https://accounts.spotify.com/authorize'
TOKEN_URL = 'https://accounts.spotify.com/api/token'
BASE_URL = 'https://api.spotify.com/v1/'
CLIENT_ID = '******'
CLIENT_SECRET = '*****'
auth_code = requests.get(AUTH_URL, {
'client_id': CLIENT_ID,
'response_type': 'code',
'redirect_uri': 'uri',
'scope': 'playlist-modify-private',
})
auth_header = base64.urlsafe_b64encode((CLIENT_ID + ':' + CLIENT_SECRET).encode())
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic %s' % auth_header.decode('ascii')
}
payload = {
'grant_type': 'authorization_code',
'code': auth_code,
'redirect_uri': 'uri',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
}
access_token_request = requests.post(url=TOKEN_URL, data=payload, headers=headers)
access_token_response_data = access_token_request.json()
access_token = access_token_response_data['access_token']
Only the auth_code for getting the code from Spotify gives <Response 200> instead the code. What could be wrong?
I tried to print the auto code but it gives <Response 200> back. This is ultimately used in the call to Spotify for the token.
Authorization Code Flow in spotify needs a server feature at application side.
It can get code value from spotify server, then request token with code.
In code flow diagram, explain detail here
I will demo with Flask
File save as spotify-client.py
from flask import Flask, request, redirect
from requests_oauthlib import OAuth2Session
from requests.auth import HTTPBasicAuth
import requests
import json
app = Flask(__name__)
AUTH_URL = 'https://accounts.spotify.com/authorize'
TOKEN_URL = 'https://accounts.spotify.com/api/token'
REDIRECT_URI = '<your callback URI>' # my case is 'http://localhost:3000/callback'
CLIENT_ID = "<your client id>"
CLIENT_SECRET = "<your client secret>"
SCOPE = [
"user-read-email",
"playlist-read-collaborative"
]
#app.route("/login")
def login():
spotify = OAuth2Session(CLIENT_ID, scope=SCOPE, redirect_uri=REDIRECT_URI)
authorization_url, state = spotify.authorization_url(AUTH_URL)
return redirect(authorization_url)
#app.route("/callback", methods=['GET'])
def callback():
code = request.args.get('code')
res = requests.post(TOKEN_URL,
auth=HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET),
data={
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI
})
return json.dumps(res.json())
if __name__ == '__main__':
app.run(port=3000,debug=True)
Steps
#1 Run Application
python spotify-client.py
#2 Open Browser and access this URL
http://localhost:3000/login
#3 Login with your Spotify credential
This login screen automatically shows to you.
#4 The access-token will shows on your browser if success login.

how do i make a user join a guild automatically using discord API? (PYTHON REQUESTS)

Im new to using discords API,
The issue im having is with Oauth2's "Access_Token", im not sure how to get an access token to have the user join the guild automatically this is the full code i have so far (i followed a tutorial to the letter literally) and im not sure what to do, i've seen other bots use it for advertising and so on but i've not been able to figure it out..
import requests
API_ENDPOINT = 'https://discord.com/api/v8'
CLIENT_ID = 'ID'
CLIENT_SECRET = 'SECRET HERE'
REDIRECT_URI = "https://google.com"
def exchange_code(code):
data = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI
}
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
r = requests.post('%s/oauth2/token' % API_ENDPOINT, data=data, headers=headers)
r.raise_for_status()
return r.json()
def add_to_guild(access_token, userID, guildID):
url = f"{API_ENDPOINT}/guilds/{guildID}/members/{userID}"
botToken = "BOT TOKEN"
data = {
"access_token" : access_token,
}
headers = {
"Authorization" : f"Bot {botToken}",
'Content-Type': 'application/json'
}
response = requests.put(url=url, headers=headers, json=data)
print(response.text)
code = exchange_code('QxoDC6swoZVJd2Gd9NCgliHy2eznBg')['access_token']
add_to_guild(code, 'USERID', 'GUILDID')
i tried using some other code and going through the documentation which unhelpfully is in javascript so i have no clue what im doing right or what im doing wrong, the expected result was to see when the user clicks the oauth2 link it will ask them if they want to allow it to join guilds for you, if they accept then it joins the guild for them

400 error on POST request for Spotify token (Python)

Using the documentation for authorisation, There are 2 steps in getting a Spotify OAuth Token
App requests authorization and receives a authorization code.
App posts a request to receive a OAuth Token.
https://developer.spotify.com/documentation/general/guides/authorization-guide/
When I try to POST a request to receive an Oath Token I get a 400 error. The code is a a bit dirty, sorry about that.
import json
import requests
from urllib.parse import urlencode
#credentials
USER_ID = '31......fbq'
CLIENT_ID = '553b......9dd'
CLIENT_SECRET = '16c40......24067b'
# encodes and prints URL
auth_url = 'https://accounts.spotify.com/authorize'
scopes_params = urlencode({
'client_id': CLIENT_ID,
'scope': 'playlist-modify-private',
'redirect_uri': 'http://localhost:8000',
'response_type': 'code'
})
scope_url = auth_url + '?' + scopes_params
print(scope_url)
response = requests.get(scope_url)
# Authorization code is copy pasted here
authorization_code = input('Enter Authorization_Code: ')
request_body_token = json.dumps({
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': 'http://localhost:8000'
})
access_token_request = requests.post(url='https://accounts.spotify.com/api/token',
data=request_body_token)
print(access_token_request.status_code)
This is the section of the authorization code I copy paste in from the redirect URI
Let me know if any additional information is needed.
I found out the issue. The request_body_token doesn't need to be converted from JSON to Python using json.dumps method, the dictionary can already be parsed in the data/body. Solution Below:
import json
import requests
from urllib.parse import urlencode
#credentials
USER_ID = '31ldam........w3wwfbq'
CLIENT_ID = '553bc4.........c0b3f09dd'
CLIENT_SECRET = '16c400........a24067b'
ENPOINT = f'https://api.spotify.com/v1/users/{USER_ID}/playlists'
# encodes and prints URL
auth_url = 'https://accounts.spotify.com/authorize'
scopes_params = urlencode({
'client_id': CLIENT_ID,
'scope': 'playlist-modify-private',
'redirect_uri': 'http://localhost:8000',
'response_type': 'code'
})
scope_url = auth_url + '?' + scopes_params
print(scope_url)
# Authorization code is copy pasted here
response = requests.get(scope_url)
authorization_code = input('Enter Authorization_Code: ')
# Here is where the error was, json.dump removed
request_body_token = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': 'http://localhost:8000'
}
access_token_request = requests.post(url='https://accounts.spotify.com/api/token', data=request_body_token)
print(access_token_request.status_code)
access_token = access_token_request.json()['access_token']

Making a request to Dynamics CRM Web API

I'm trying to make an app that makes requests to Dynamics CRM Web API from python using urllib2.
So far I can login an user with an Azure application by making a post request to https://login.microsoftonline.com/common/oauth2/authorize
then with the retrieved authorization_code I can get the access_token, refresh_token and others with urllib2
url = 'https://login.microsoftonline.com/common/oauth2/token'
post_fields = {'grant_type': 'authorization_code',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': REDIRECT_URI,
'resource': 'https://graph.microsoft.com',
'code': code}
request = Request(url, urlencode(post_fields).encode())
resp = urlopen(request).read().decode()
resp = json.loads(resp)
refresh_token = resp['refresh_token']
id_token = resp['id_token']
id_token = jwt.decode(id_token,verify=False)
access_token = resp['access_token']
Then I tried to make another post request by using the access_token but had no luck.
I keep getting:
HTTP Error 401: Unauthorized
Just as a test I make a post directly to .dynamics.com/api/data/v8.1/leads
as follows:
url = 'https://<company_uri>.dynamics.com/api/data/v8.1/leads'
post_fields = {"name": "Sample Account",
"creditonhold": "false",
"address1_latitude": 47.639583,
"description": "This is the description of the sample account",
"revenue": 5000000,
"accountcategorycode": 1
}
request = Request(url, urlencode(post_fields).encode())
request.add_header('Authorization', 'Bearer ' + access_token )
request.add_header("Content-Type", "application/json; charset=utf-8")
request.add_header('OData-MaxVersion','4.0')
request.add_header('OData-Version','4.0')
request.add_header('Accept','application/json')
resp = urlopen(request).read().decode()
But i keep getting the same 401 error code.
I've looked all over msdn documentation but didn't find the way to do this directly without using any library, I just want to use a simple post request.
Since the error code says Unauthorized I think the access_token must be sent in some other way.
Can someone help me on how to correctly use the access_token on Dynamics CRM?
Thanks!
The access token you got back is for the Azure AD Graph API. Not Dynamics CRM.
To call that, you must ask for an access token with resource set to Dynamics CRM API's App ID URI, not https://graph.windows.net.
According to documentation you should set resource to https://<company_uri>.crm.dynamics.com.
So when you are retrieving token:
url = 'https://login.microsoftonline.com/common/oauth2/token'
post_fields = {'grant_type': 'authorization_code',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': REDIRECT_URI,
'resource': 'https://<company_uri>.crm.dynamics.com',
'code': code}

"Error parsing JSON" when using Spotify API

I am learning Python and I am trying to create a playlist using the Spotify web api but get a http 400 error: Error parsing json. I guess it has to do with an incorrect variable type in the token but I am having a really hard time debugging it as I can't figure out a way to see the post request in raw format.
Posting through the API requires authorizing and this is the script I've created for that:
import requests
import base64
requests.packages.urllib3.disable_warnings()
client_id = 'ID'
client_secret = 'SECRET'
redirect_uri = 'http://spotify.com/'
scope = 'playlist-modify-private playlist-read-private'
def request_token():
# 1. Your application requests authorization
auth_url = 'https://accounts.spotify.com/authorize'
payload = {'client_id': client_id, 'response_type':'code','redirect_uri':redirect_uri}
auth = requests.get(auth_url,params = payload)
print '\nPlease go to this url to authorize ', auth.url
# 2. The user is asked to authorize access within the scopes
# 3. The user is redirected back to your specified URI
resp_url = raw_input('\nThen please copy-paste the url you where redirected to: ')
resp_code= resp_url.split("?code=")[1].split("&")[0]
# 4. Your application requests refresh and access tokens
token_url = 'https://accounts.spotify.com/api/token'
payload = {'redirect_uri': redirect_uri,'code': resp_code, 'grant_type': 'authorization_code','scope':scope}
auth_header = base64.b64encode(client_id + ':' + client_secret)
headers = {'Authorization': 'Basic %s' % auth_header}
req = requests.post(token_url, data=payload, headers=headers, verify=True)
response = req.json()
return response
This is the function actually trying to create the playlist using the authorization token (import authorizer is the function above):
import requests
import authorizer
def create_playlist(username, list_name):
token = authorizer.request_token()
access_token = token['access_token']
auth_header = {'Authorization': 'Bearer {token}'.format(token=access_token), 'Content-Type': 'application/json'}
api_url = 'https://api.spotify.com/v1/users/%s/playlists' % username
payload = {'name': list_name, 'public': 'false'}
r = requests.post(api_url, params=payload, headers=auth_header)
But whatever I try it only leads to a 400 error. Can anyone please point out my error here?
Solved by adding a json.dumps for the input: json.dumps(payload) and changing the payload to be 'data' and not 'params' in the request.
So the new functioning request equals:
r = requests.post(api_url, data=json.dumps(payload), headers=auth_header)

Categories

Resources