401 Client Error: Unauthorized url. Flask python - python

I have a program that Authenticate with API and when logged in search by Id in contacts on this API.
logging in works fine but when I try to find contact this error happen:
401 Client Error: Unauthorized for url:https://api.moxiworks.com/api/contacts/12345678
and same problem happen when try it on Postman like in this image:
after log in I redirected to home route and here is the code:
#app.route('/home', methods=["GET", "POST"])
#login_required
def home():
if request.method == "POST":
found = request.form.get('id')
#base64 encoded Partner ID and Partner Secret
sample_string = ('%s:%s' % (os.getenv("CLIENT_ID"), os.getenv("CLIENT_SECRET"))).replace('\n', '')
sample_string_bytes = sample_string.encode("ascii")
base64_bytes = base64.b64encode(sample_string_bytes)
base64_string = base64_bytes.decode("ascii")
if not found:
return render_template('apology', err='must provide id')
try:
token = session['token']
response = moxi.get(f'https://api.moxiworks.com/api/contacts/{found}',
token=token,
headers={
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic %s' % base64_string,
'Accept': 'application/vnd.moxi-platform+json;version=1',
'Cookie': '_wms_svc_public_session'
})
if response.status_code == 429:
flash('too many requests, wait for 60 seconds then will get your results')
time.sleep(60)
response = moxi.get(f'https://api.moxiworks.com/api/contacts/{found}',
token=token,
headers={
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic %s' % base64_string,
'Accept': 'application/vnd.moxi-platform+json;version=1',
'Cookie': '_wms_svc_public_session'
})
# If the response was successful, no Exception will be raised
response.raise_for_status()
except HTTPError as err:
return render_template('apology.html', err=err)
except Exception as err:
return render_template('apology.html', err=err)
else:
try:
contact = response.json()
return render_template('data.html',
contact1=contact['agent_uuid'], contact2=contact['moxi_works_agent_id'],
contact3=contact['partner_contact_id'], contact4=contact['contact_name'],
contact5=contact['primary_email_address'], contact6=contact['secondary_email_address'],
contact7=contact['primary_phone_number'], contact8=contact['secondary_phone_number'])
except (KeyError, TypeError, ValueError) as err:
return render_template('apology.html', err=err)
else:
return render_template('home.html')
What I miss? or what is wrong in my code?
here is the auth register:
moxi = oauth.register(
name='moxi',
client_id=os.getenv("CLIENT_ID"),
client_secret=os.getenv("CLIENT_SECRET"),
access_token_url='https://sso.moxiworks.com/oauth/token',
access_token_params={'grant_type': 'authorization_code'},
authorize_url='https://sso.moxiworks.com/oauth/authorize',
authorize_params={'response_type': 'code'},
api_base_url='https://api.moxiworks.com/api/contacts/',
userinfo_endpoint='https://sso.moxiworks.com/agent/profile', # This is only needed if using openId to fetch user info
client_kwargs = {
'scope': 'profile',
'token_endpoint_auth_method': 'client_secret_basic',
'token_placement': 'header',
}
)
please help me to figure out how to fix this?
thanks in advance.

The error shows that you have not included your authorisation header. According to the Basic Authentication standard (RFC 7617) used here, you should include the access token in the Authorization header instead of the parameter. As such, it should look something like this enter image description here.
Or on the python code, it will look like this
import requests
url = "https://example.com/api/contacts/1234"
payload = {}
headers = {'Authorization': 'Basic <access_token>'}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)

Related

error in finding Spotify user ID with python

hey im trying to fetch my spotify user ID in order to create a playlist on my profile
im able to find the songs im interested in using the spotify API but im stuck after that
this is my code to find user ID
`
# Use the Spotify API to get the authenticated user's ID
headers = {
'Authorization': 'Bearer ' + access_token
}
response = requests.get('https://api.spotify.com/v1/me', headers=headers)
if response.status_code == 200:
# Success!
user_id = response.json()['id']
else:
# Error occurred
print('Error:', response.status_code)
it keeps giving me a 401 error
after that im trying to create a playlist and add songs to that playlist
`
# Use the Spotify API to create a new playlist
headers = {
'Authorization': 'Bearer ' + access_token,
'Content-Type': 'application/json'
}
data = {
'name': 'Sample Playlist',
'public': True
}
response = requests.post('https://api.spotify.com/v1/me/playlists', headers=headers, json=data)
if response.status_code == 201:
# Success!
playlist_id = response.json()['id']
else:
# Error occurred
print('Error:', response.status_code)
``
please help
i tries using the endpoints in the docs but no solution

Schiphol flight api, get flight information with python gets error

I'm trying to get data from a public api from schiphol (airport in Amsterdam).
Im getting this api from https://api.schiphol.nl/public-flights/flights.
I'm using python to get the flight data. In my code I get the error that the "app_id" is none while this is filled in....
the full error from the console:
Usage: flight_info_api.py [options]
flight_info_api.py: error: Please provide an app id (-i, --app_id)
Can anybody see what is going wrong?
My code:
import requests
import sys
import optparse
def callPublicFlightAPI(options):
url = 'https://api.schiphol.nl/public-flights/flights'
headers = {
'resourceversion': 'v4',
'app_id': 'b209eb7f',
'app_key': '0b6c58b5ae4595dd39785b55f438fc70'
}
try:
response = requests.request('GET', url, headers=headers)
except requests.exceptions.ConnectionError as error:
print(error)
sys.exit()
if response.status_code == 200:
flightList = response.json()
print('found {} flights.'.format(len(flightList['flights'])))
for flight in flightList['flights']:
print('Found flight with name: {} scheduled on: {} at {}'.format(flight['flightName'],
flight['scheduleDate'],
flight['scheduleTime']))
else:
print('''Oops something went wrong Http response code: {}{}'''.format(response.status_code, response.text))
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option('-i', '--app_id', dest='app_id',
help='App id used to call the API')
parser.add_option('-k', '--app_key', dest='app_key',
help='App key used to call the API')
(options, args) = parser.parse_args()
if options.app_id is None:
parser.error('Please provide an app id (-i, --app_id)')
if options.app_key is None:
parser.error('Please provide an app key (-key, --app_key)')
callPublicFlightAPI(options)
You need to add this to your headers:
'Accept': 'application/json'
Good luck.
EDIT:
Basically, Since you would like to receive your data as json, You will have to add 'Accept': 'application/json' to your headers. In this case, your headers will look like this:
headers = {
'Accept': 'application/json',
'resourceversion': 'v4',
'app_id': YOUR_APP_ID,
'app_key': YOUR_APP_KEY
}
And when you are going to make a request, you have to add the headers in the parameter. Your request is going to look like this:
response = requests.get(URL, headers=headers)
I hope this helps!

Basic Authentication returns 401 Client Error but works in postman

I have gone through number of similar posts related to firing GET requests with Basic Auth (eg: Python, HTTPS GET with basic authentication), still can't figure out the problem. I keep getting the error requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url
With the same credentials, headers tried the same in postman it works as expected. Verified that base64encoded value for the api_key, password is exactly same as the value used in postman, so I don't think its encoding or resource access permission problem.
python -V
Python 3.6.4 :: Anaconda, Inc.
Approach 1
api_key = 'some_api_key'
password = 'some_password'
headers = {'accept': 'application/json'}
url = 'https://test.access.com/this/url'
api_key_password = "%s:%s" % (api_key, password)
b64_encoded = b64encode(bytes(api_key_password, 'utf-8')).decode("ascii")
headers['authorization'] = 'Basic %s' % b64_encoded
response = requests.get(url,
headers=headers)
if (response.ok):
json_data = json.loads(response.content)
print (json_data)
else:
print (response)
response.raise_for_status()
Approach 2
api_key = 'some_api_key'
password = 'some_password'
url = 'https://test.access.com/this/url'
headers = {
'accept': 'application/json',
}
response = requests.get(url, headers=headers, auth=(api_key, password))
print (response.ok)
if (response.ok):
json_data = json.loads(response.content)
print (json_data)
else:
print (response)
response.raise_for_status()
Can you please provide some pointers?
I had a similar issue (although in .NET Framework).
In my case the reason was that I was using the url without a forward slash in the end and the API apparently does not support that.
So https://test.access.com/this/url
Throws 401 error Unauthorized
but
https://test.access.com/this/url/
Returns 200 OK.
Older post but I had a similar issue. Postman will cache your JSESSIONID. Be sure you are clearing out that cookie while testing. If you are hitting an API that requires a login API call to establish a session before you can make subsequent API calls, this Postman behavior can produce a false sense of security.
In this situation with Python requests, it can be handled with code similar to what I've provided below:
import requests,json
loginAPI = "https://myapi.myco.comv/someuri/someuri/users/login"
someHTTPGetAPI = "https://myapi.myco.com/someuri/someuri/someservice"
username = "myuser"
password = "mypass"
headers = {
"Content-Type": "application/json",
"login": username,
"password": password
}
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
verify=False
session = requests.Session()
sessionResponse = session.get(url=loginURL,headers=headers, verify=verify)
if sessionResponse.status_code == 200:
getResponse = session.get(url=someHTTPGetAPI)
if getResponse.status_code == 200:
responseJSON = agentStatus.json()

Standard Python Auth0 project does not seem to authenticate

I am trying to run a standard Python Auth0 project available here
If you are logged in it comes with valid pre-generated keys in .env file and I checked them anyway, so question is similar to Django + Auth0 JWT authentication refusing to decode but answers there do not help.
server.py from example:
import jwt
import base64
import os
from functools import wraps
from flask import Flask, request, jsonify, _request_ctx_stack
from werkzeug.local import LocalProxy
from dotenv import Dotenv
from flask.ext.cors import cross_origin
env = None
try:
env = Dotenv('./.env')
client_id = env["AUTH0_CLIENT_ID"]
client_secret = env["AUTH0_CLIENT_SECRET"]
except IOError:
env = os.environ
app = Flask(__name__)
# Format error response and append status code.
def handle_error(error, status_code):
resp = jsonify(error)
resp.status_code = status_code
return resp
def requires_auth(f):
#wraps(f)
def decorated(*args, **kwargs):
auth = request.headers.get('Authorization', None)
if not auth:
return handle_error({'code': 'authorization_header_missing', 'description': 'Authorization header is expected'}, 401)
parts = auth.split()
if parts[0].lower() != 'bearer':
return handle_error({'code': 'invalid_header', 'description': 'Authorization header must start with Bearer'}, 401)
elif len(parts) == 1:
return handle_error({'code': 'invalid_header', 'description': 'Token not found'}, 401)
elif len(parts) > 2:
return handle_error({'code': 'invalid_header', 'description': 'Authorization header must be Bearer + \s + token'}, 401)
token = parts[1]
try:
payload = jwt.decode(
token,
base64.b64decode(client_secret.replace("_","/").replace("-","+")),
audience=client_id
)
except jwt.ExpiredSignature:
return handle_error({'code': 'token_expired', 'description': 'token is expired'}, 401)
except jwt.InvalidAudienceError:
return handle_error({'code': 'invalid_audience', 'description': 'incorrect audience, expected: ' + client_id}, 401)
except jwt.DecodeError:
return handle_error({'code': 'token_invalid_signature', 'description': 'token signature is invalid'}, 401)
except Exception:
return handle_error({'code': 'invalid_header', 'description':'Unable to parse authentication token.'}, 400)
_request_ctx_stack.top.current_user = user = payload
return f(*args, **kwargs)
return decorated
# Controllers API
#app.route("/ping")
#cross_origin(headers=['Content-Type', 'Authorization'])
def ping():
return "All good. You don't need to be authenticated to call this"
#app.route("/secured/ping")
#cross_origin(headers=['Content-Type', 'Authorization'])
#cross_origin(headers=['Access-Control-Allow-Origin', '*'])
#requires_auth
def securedPing():
return "All good. You only get this message if you're authenticated"
if __name__ == "__main__":
app.run(host='0.0.0.0', port = int(os.environ.get('PORT', 3001)))
http://localhost:3001/secured/ping gives:
{
"code": "authorization_header_missing",
"description": "Authorization header is expected"
}
Headers:
Request URL:http://localhost:3001/secured/ping
Request Method:GET
Status Code:401 UNAUTHORIZED
Remote Address:127.0.0.1:3001
Response Headers
Content-Length:98
Content-Type:application/json
Date:Wed, 15 Jun 2016 13:15:57 GMT
Server:Werkzeug/0.11.4 Python/2.7.6
Request Headers
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Cache-Control:max-age=0
Connection:keep-alive
Host:localhost:3001
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/50.0.2661.102 Chrome/50.0.2661.102 Safari/537.36
In the document you linked under the section Call Your API the request is done with the header Authorization for example if you need to connect with curl use the following option:
--header 'Authorization: Bearer YOUR_ID_TOKEN_HERE'
This Authorization header is then parsed by your python code.
But as you can see in your supplied Request Headers there is no Authorization field in the header.
Also, the code sample is not sending any requests but rather serving them, so no changes to the code must be made.
Rather, to request the secured version of ping, you need to request it with one of the methods described in the linked document. Accessing the secured page in a browser is not possible without javascript.

Python Linkedin API OAuth2 HTTP Error 401: Unauthorized

I am trying to Share a Post on Linkedin on user's behalf.
I took the user through authentication process to generate oauth2 token. I have the token but now i am stuck how to use it. All the help i found on the internet was regarding Oauth not Oauth2. I am trying to send the request but i am getting HTTP Error 401: Unauthorized. Below is my code...
import urllib2, cookielib
cookie_jar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))
urllib2.install_opener(opener)
xml_request = ..... XML
headers={'Content-Type': 'application/xml'}
url = "http://api.linkedin.com/v1/people/~/shares/?oauth2_access_token=XXXX"
req = urllib2.Request(url, data=xml_request, headers = headers)
rsp = opener.open(req)
content = rsp.read()
I have checked and the token is valid i am getting Network Updates using the same token... I have searched and searched but still no help on Oauth2. All the Linkedin Clients i have seen in using Oauth not Oauth2..
Please help me out on how to send this request.
If anyone know any api or client which uses oauth2 please let me know..
Thanks in advance for your help
I wrote below code to Share Content on linkedin using OAuth 2.0
import requests
import json
def make_request(method, url, token ,data=None, params=None, headers=None, timeout=60):
headers = {'x-li-format': 'json', 'Content-Type': 'application/json'}
params = {}
kw = dict(data=data, params=params, headers=headers, timeout=timeout)
params.update({'oauth2_access_token': token})
return requests.request(method.upper(), url, **kw)
def submit_share(comment, title, description, submitted_url, submitted_image_url, token):
post = {
'comment': comment,
'content': {
'title': title,
'submitted-url': submitted_url,
'submitted-image-url': submitted_image_url,
'description': description
},
'visibility': {
'code': 'anyone'
}
}
url = 'https://api.linkedin.com/v1/people/~/shares'
try:
response = make_request('POST', url, token,data=json.dumps(post))
response = response.json()
return response
except Exception:
return False
I hope this code helps anyone.
Regards

Categories

Resources