Can't access API with access token authorization in python automated tests - api

I am writing automated api tests in python for rest api's. I have the access token but it says "Access denied". The same token works with postman request. Can someone let me know if I am missing something in my code?
import json
import requests
import urllib3
BASE_URL = <my_url>
mytoken = <my_token>
head = {'Authorization': 'Bearer ' + mytoken}
response = requests.get(BASE_URL,headers = head)
print(json.dumps(response.json(), indent=4))
print(response.status_code)
Output I get :
{
"Error": "Access Denied"
}
403
Expected result :
It should return a JSON body and status code 200 with content

Related

OAuth2: Unable to Authenticate API request

Been tasked to export forms and items from Podio using the API. Trying to do this with straight Python and Requests instead of the canned API tool. Am successful at retrieving the access and refresh tokens, but am unable to make the simplest Get request. The response has the error:
"error_description":"Authentication as None is not allowed for this method"
Tried this with 2 versions of using OAuth2 in Requests, both return that response.
What is it trying to tell me? Aside from giving the token, is there any other authentication attributes required?
client = BackendApplicationClient(client_id=CLIENT_ID)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url=auth_url, client_id=CLIENT_ID,
client_secret=CLIENT_SECRET)
print('token:', token)
access_token = token["access_token"]
api_url = base_url + 'user/status'
r = oauth.get(api_url)
print(r.text)
headers = {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
"Authorization": "Bearer " + token["access_token"]}
response = requests.get(api_url, headers=headers, verify=True)
print(response.text)
Here is full response:
{"error_parameters":{},"error_detail":null,"error_propagate":false,"request":{"url":"http://api.podio.com/user/status","query_string":"","method":"GET"},"error_description":"Authentication as None is not allowed for this method","error":"forbidden"}

Podio API returning "unauthorized" response 401

I'm working on Podio API and as of now access API endpoints with the Python's (3.10.2) requests:
import requests as rq
def podio_api(url, payload=None, get=True):
"""Generic function to return responses from API,
it works with both GET and POST requests"""
url = "https://api.podio.com/" + url
headers = {
"Authorization": "OAuth2 " + get_token(),
"content-type": "application/json",
}
if get:
return rq.get(url, params=payload, headers=headers)
else:
return rq.post(url, json=payload, headers=headers)
The get_token() function successfully returns an access token (that's refreshed, so it's not expired). However, podio_api() started returning a 401 response ("unauthorized").
{'error_parameters': {}, 'error_detail': None, 'error_propagate': False, 'request': {'url': 'http://api.podio.com/app/<app_id>', 'query_string': '', 'method': 'GET'}, 'error_description': 'invalid_request', 'error': 'unauthorized'}
The app was working till yesterday.
Surprisingly, pypodio2 authorization works fine but I'd avoid it as it's an antique package.

Cannot POST request using service account key file in Python, getting 'Invalid IAP credentials: Unable to parse JWT', '401 Status Code'

I am trying to send a POST request to a Google App Engine service with a JSON body accompanied by an authorization token. I am generating the access token from a local service account key JSON file. The code below is generating a credential but finally the authorization is being rejected. I also tried different ways already. Even tried writing the request in Postman with a Bearer token in the Header, or even as a plain cURL command. But whatever I try, getting a 401 authentication error. I need to make sure whether the problem is in my side or on the other side with the service. Explored every documentation avaliable but no luck.
from google.auth.transport import requests
from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession
CREDENTIAL_SCOPES = ["https://www.googleapis.com/auth/cloud-platform"]
CREDENTIALS_KEY_PATH = 'my-local-service-account-key-file.json'
#the example service url I am trying to hit with requests
url = 'https://test.appspot.com/submit'
headers = {"Content-Type": "application/json"}
#example data I am sending with the request body
payload = {
"key1": "value 1",
"key2": "value 2"
}
credentials = service_account.Credentials.from_service_account_file(
CREDENTIALS_KEY_PATH,
scopes=CREDENTIAL_SCOPES
)
credentials.refresh(requests.Request())
authed_session = AuthorizedSession(credentials)
response = authed_session.request('POST',
url,
headers=headers,
data=payload
)
#adding some debug lines for your help
print(response.text)
print(response.status_code)
print(response.headers)
Getting the Output:
Invalid IAP credentials: Unable to parse JWT
401
{'X-Goog-IAP-Generated-Response': 'true', 'Date': 'Mon, 03 May 2021 06:52:11 GMT', 'Content-Type': 'text/html', 'Server': 'Google Frontend', 'Content-Length': '44', 'Alt-Svc': 'h3-29=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"'}
IAP expects a JWT(OpenID Connect (OIDC)) token in the Authorization header while your method will attach an access token the the Authorization header instead. Take a look at the below code snippet to make a request to an IAP secured resource.
Your code needs to be something like the following:
from google.auth.transport.requests import Request
from google.oauth2 import id_token
import requests
def make_iap_request(url, client_id, method='GET', **kwargs):
"""Makes a request to an application protected by Identity-Aware Proxy.
Args:
url: The Identity-Aware Proxy-protected URL to fetch.
client_id: The client ID used by Identity-Aware Proxy.
method: The request method to use
('GET', 'OPTIONS', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE')
**kwargs: Any of the parameters defined for the request function:
https://github.com/requests/requests/blob/master/requests/api.py
If no timeout is provided, it is set to 90 by default.
Returns:
The page body, or raises an exception if the page couldn't be retrieved.
"""
# Set the default timeout, if missing
if 'timeout' not in kwargs:
kwargs['timeout'] = 90
# Obtain an OpenID Connect (OIDC) token from metadata server or using service
# account.
open_id_connect_token = id_token.fetch_id_token(Request(), client_id)
# Fetch the Identity-Aware Proxy-protected URL, including an
# Authorization header containing "Bearer " followed by a
# Google-issued OpenID Connect token for the service account.
resp = requests.request(
method, url,
headers={'Authorization': 'Bearer {}'.format(
open_id_connect_token)}, **kwargs)
if resp.status_code == 403:
raise Exception('Service account does not have permission to '
'access the IAP-protected application.')
elif resp.status_code != 200:
raise Exception(
'Bad response from application: {!r} / {!r} / {!r}'.format(
resp.status_code, resp.headers, resp.text))
else:
return resp.text
Note: The above method works with implicit credentials that can be set by running command: export GOOGLE_APPLICATION_CREDENTIALS=my-local-service-account-key-file.json to set the path to your service account in the environment and then run the python code from the same terminal.
Take a look at this link for more info.

Can't set authorization and token in headers with axios in VueJS

I'm trying to set a JWT token authentication on a VueJS client and PHP API (using Zend and firebase).
I manage to log an user in with the creation of a JWT token stored in LocalStorage. Now I would like to send back this token to the API (so as to the API decode the JWT and return associated infos). I try to set the "Authorisation: Bearer + token" in the header from VueJS using axios but I always have a problem.
Here is a code snippet :
function getInfos() {
return axios({
method: 'get',
url: MYURL,
headers: {
Authorization: 'Bearer ' + localStorage.getItem('user')
}
})
.catch(handleResponse)
}
First I got this error :
Access to XMLHttpRequest at 'MYURL' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Then I don't have any Authorization in header when I want it in my PHP API :
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: *');
$request = new Request();
I know that I probably have to use
axios.defaults.headers.post or maybe axios.interceptors but I'm a beginner so I have no idea how to use it properly..
I hope someone will be able to help me ! Thank you
I think * doesn't work when setting custom headers you have to Type in header('Access-Control-Allow-Headers: Authorization') atleast that's an issue i had

GET API code request failure

I just started learning how to use API and I found some really usefull websites and apps like Postman and import.io yet I'm having problems finishing it without help.
I started my little project by getting a working api from import.io (It reads a website and can give you a working API that finds the info in the website)
My REST API looks like this:
https://extraction.import.io/query/runtime/7629f27e-ceee-4ce2-9a1c-cede623d2fc0?_apikey=[apiKey]&url=http%3A%2F%2Fimdb.com
To test and make sure it's working I used postman app and then found a neat feature - code generation.
The app generated this code:
import http.client
conn = http.client.HTTPSConnection("extraction.import.io")
headers = {
'cache-control': "no-cache",
'postman-token': "2087cc79-77b5-0cb9-aa06-adc642978287"
}
conn.request("GET", "/query/runtime/1ac40e3e-f3eb-4290-88c0-e2651b8194a5?_apikey=[apiKey]&url=http%253A%252F%252Fwww.leagueofgraph.com", headers=headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
however the result is:
{
"message" : "Your extraction request has failed.",
"code" : 1003
}
What am I doing wrong?
The code that has been generated has double escaped the "http://"
it should be http%3A%2F%2F not http%253A%252F%252F
Try this corrected code:
import http.client
conn = http.client.HTTPSConnection("extraction.import.io")
headers = {
'cache-control': "no-cache",
'postman-token': "2087cc79-77b5-0cb9-aa06-adc642978287"
}
conn.request("GET", "/query/runtime/1ac40e3e-f3eb-4290-88c0-e2651b8194a5?_apikey=[apiKey]&url=http%3A%2F%2Fwww.leagueofgraph.com", headers=headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))