i am trying to call my jwt authenticated django api that lives on an EC2 instance from my home laptop. the API will return me a auth key but when i try to use the auth key it tells me im not authorized. I have provided an example of the various methods i have tried to use to get this to work.
is there anything specifically i am doing wrong in this code that would warrant my code to consistently return 401 error? when asking for an authenticated API with a JWT token is there anything specifically i need to do or a specific way i need to set my headers so that i can get a value to return? or does this look like an issue with the backend?
import requests
from urllib2 import Request, urlopen
import jwt
from requests_jwt import JWTAuth, payload_method
import json
def tryme(chats, payload, jwt):
#method1
res = requests.post(chats, json=payload)
print res.status_code
# error 401
# method2
req = requests.get(chats, params=payload)
print req.status_code
# error 401
# method3
req = Request(chats)
req.add_header('Authorization', 'Token token={}'.format(auth['token']))
req.add_header('content-type', 'application/json')
res = urlopen(req)
print res.status_code
# error 401
#method4
token = JWTAuth(jwt['token'])
out = requests.get(chats, auth=token)
print out.status_code
# error 401
out = requests.post(chats, auth=token)
print out.status_code
# error 401
def main():
payload = {
'username': 'testuser',
'password': 'test1234'
}
base_url = 'https://www.example.com/api/v1/'
api_auth = base_url + 'api-token-auth/'
chats = base_url + 'chats/'
auth = json.loads(requests.post(api_auth, json=payload).content)
# returns auth token
payload = {'Authorization': 'Token {}'.format(auth['token']), 'content-type': 'application/json'}
tryme(chats, payload, auth)
payload = {'Authorization': 'Bearer {}'.format(auth['token']), 'content-type': 'application/json'}
tryme(chats, payload, auth)
payload = {'Authorization': 'JWT {}'.format(auth['token']), 'content-type': 'application/json'}
tryme(chats, payload, auth)
if __name__ == '__main__':
main()
this was solved. however i upgraded to python3.
import requests
import urllib3
urllib3.disable_warnings()
payload = {
'username': 'testuser',
'password': 'test1234'
}
base_url = 'https://www.example.com/api/v1/'
api_auth = base_url + 'api-token-auth/'
chats = base_url + 'chats/'
# get jwt token from login credentials
auth = json.loads(requests.post(api_auth, json=payload).content)['token']
# correctly format the call which was my primary issue above.
payload = {'Authorization': 'JWT {}'.format(auth)}
# in python3 use urllib3.
http = urllib3.PoolManager()
res = http.request('GET', chats, headers=payload)
print(res.data)
in python2:
import requests
payload = {
'username': 'testuser',
'password': 'test1234'
}
base_url = 'https://www.example.com/api/v1/'
api_auth = base_url + 'api-token-auth/'
chats = base_url + 'chats/'
# get jwt token from login credentials
auth = json.loads(requests.post(api_auth, json=payload).content)['token']
# correctly format the call which was my primary issue above.
payload = {'Authorization': 'JWT {}'.format(auth)}
# make sure you are using the right request (GET vs POST)
out = requests.get(chats, headers=token)
print out.content
Related
I am trying to make a simple request to get the access token from Citrix ShareFile, but it's throwing 400 error.
I am going exactly as it's mentioned in the documentation, except changing Python2 code with HTTPLib, with Python3 code with Requests. The code is:
url = 'https://{my_domain}.sharefile.com/oauth/token'
headers = {'Content_Type': 'application/x-www-form-urlencoded'}
params = {'grant_type':'password', 'client_id':my_client_id, 'client_secret':my_client_secret, 'username':my_username, 'password':my_password}
response = requests.post(url, params=params, headers = headers)
print(response.status_code, response.reason)
I get the following response:
400 Bad Request
I also added urllib.parse.urlencode to params, but am still getting the same response error
response = requests.post(url, params=urllib.parse.urlencode(params), headers = headers)
Request guidance on what am I doing wrong. TIA
It could be the password, in the context of Sharefile it means app_password and not the password used to login to website. Or response_type to 'code'.
SF Auth is through OAuth2 with a GrandType: OAuth2 Password Grant
This way works for me:
url = 'https://{my_domain}.sharefile.com/oauth/token'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
data = {
'response_type': 'code',
'grant_type': 'password',
'client_id': '<YOUR CLIENT ID>',
'client_secret': '<YOUR SECRET>',
'username': '<USERNAME>',
'password': '<APP_PASSWORD>' # not regular password to login using web
}
response = requests.post(url, data=data, headers=headers)
Response contains token and refresh token.
When I add content-type my issue solved.
Check and add valid content-type
I am following a simple example (or what I thought was simple) of creating a python script that used the REST api to connect to wordpress.
However, I am getting a 403 error. My credentials are correct because I can log in with them.
I have been working over this for awhile now. Can anyone see where my error might be? Thank you.
url = "https://prod-wp.xxxxxx.com/wp-json/wp/v2/posts"
user = "xxxxxx"
password = "xxxxxxxx"
credentials = user + ':' + password
token = base64.b64encode(credentials.encode())
header = {'Authorization': 'Basic ' + token.decode('utf-8')}
response = requests.get(url , headers=header)
print(response)
<Response [403]>
EDIT
I have changed the code and this seems to work.
import requests
import os
from dotenv import load_dotenv
load_dotenv()
BASE_URL = 'https://website.com/wp-json'
WP_URL = os.getenv("WP_URL")
WP_USERNAME = os.getenv("WP_USERNAME")
WP_PASSWORD = os.getenv("WP_PASSWORD")
def get_headers():
wp_credentials = {'username': WP_USERNAME, 'password': WP_PASSWORD}
jwt_response = requests.post(f'{BASE_URL}/jwt-auth/v1/token', json=wp_credentials)
jwt_token = jwt_response.json()['token']
headers = {
"Authorization": "Bearer %s" % jwt_token,
"Content-Type": "application/json",
"Accept": "application/json",
}
print(f'Headers are equal to: {headers}')
return headers
get_headers()
So i'm writing a program that post's data to a url and get's the response. In postman it requires a token. So when I tried to make it in python it's giving me a response [401].
The problem I have is trying to get the token first and then passing it to my post_data method.
I'm going to put *** by the URL and username and password for privacy concerns.
import requests
import json
import pprint
import urllib
def get_token():
tokenurl='***'
data={
'grant_type':'password',
'username':'***',
'password':'***'
}
token=requests.post(tokenurl,data=data)
print(token)
get_token()
def post_data():
url1='***'
data={"***"
}
data_json = json.dumps(data)
headers = {'Content-type': 'application/json'}
response = requests.post(url, data=data_json, headers=headers)
pprint.pprint(response.json())
In the post_data() function, you can add your generated token to the headers
headers = {'Content-type': 'application/json','Authorization': 'token ***'}
*** is your generated token
i'm working on settin up a rest api with python, however i'm having some problem getting it to work.
I'm working with the TV DB rest api: https://api.thetvdb.com/swagger
and using python with Requests library to pull out the information.
My code is currently:
import json
import requests
URL = "https://api.thetvdb.com/"
API_KEY = "Api_key"
USER_KEY = "Key"
USERNAME = "Name"
headers = {"Accept": "application/json"}
params = {
"apikey": API_KEY,
"userkey": USER_KEY,
"username": USERNAME
}
resp = requests.post(URL + "login/", headers = headers ,params=params)
if resp.status_code != 200:
print('error: ' + str(resp.status_code))
else:
print('Success')
So far i'm only getting error code 401, not sure why.
Solved:
2 Things needed to be changed
1. The resp was changed into:
resp = requests.post(URL + "login/", headers = headers, data=json.dumps(params))
The header had to have
"Content-Type": "application/json"
added to it :) It's now working, thanks everyone
The login parameters probably need to be a JSON-encoded string POSTed as the body of the message.
Try resp = requests.post(URL + "login/", headers = headers, data=json.dumps(params))
I have tried this to update my access token
import urllib
endpoint='https://accounts.google.com/o/oauth2/token'
data={'client_id':'25********15-6*********************7f.apps.googleusercontent.com','client_secret':'4********Pj-K*****x4aM','refresh_token':'1/tP************************O_XclU','grant_type':'refresh_token'}
encodedData=urllib.urlencode(data)
from httplib2 import Http
h = Http()
resp, content = h.request(endpoint, "POST", encodedData)
But got the error message
'{\n "error" : "invalid_request",\n "error_description" : "Required parameter is missing: grant_type"\n}'
You should specify the headers in your request like this:
resp, content = h.request(uri=endpoint,
method="POST",
body=encodedData,
headers={'Content-type': 'application/x-www-form-urlencoded'})
old-refresh_token is the refresh token you have
CLIENT_ID,CLIENT_SECRET are the credentials you can find those in google developers console
http = httplib2.Http()
TOKEN_URL = "https://accounts.google.com/o/oauth2/token"
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
parameters = urllib.urlencode({'refresh_token': old-refresh_token, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'grant_type': 'refresh_token'})
resp, response_token = http.request(TOKEN_URL, method='POST', body=parameters, headers=headers)
token_data = json.loads(response_token)
access_token = token_data['access_token']
the variable access_token now holds your access token
try it out