Need to access to the Bynder API - api

I am trying to connect to the Bynder API using Python and the documentation https://bynder.docs.apiary.io/ but I can make it to connect to the Analytics endpoint https://bynder.docs.apiary.io/#reference/analytics because I received a 401 response
I have the following code :
from bynder_sdk import BynderClient
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Origin': 'Allowed domain for cross-domain requests. Only required if any domains were specified in \'Set HTTP access control (CORS)\' for the OAuth application.',
'Authorization': 'Basic b64("abcd":"abcd")'
}
bynder_client = BynderClient(
domain='abcd.com',
redirect_uri='https://abcd.com/v7/analytics/api/v1/asset/view',
client_id='abcd',
client_secret='abcd',
scopes ="offline analytics.api:read",
grant_type="client_credentials"
)
print(bynder_client.get_authorization_url())
print(bynder_client.get_authorization_url()[1])
params = {"limit":"100", "fromDateTime":"2022-01-01T01:00","toDateTime":"2022-06-01T01:00" }
api_call_headers = {'Authorization': 'Token ' + bynder_client.get_authorization_url()[1]}
api_call_response = requests.get("https://abcd.abcd.com/v7/analytics/api/v1/asset/view", headers=api_call_headers, params=params, verify=False)
can someone help me to understand how to Autorise using OAuth 2.0 the Client ID and Client Secret and use the Analytics endpoint? I have all the details in the bynder_client = BynderClient()
Thanks

For anyone reference this his how I ended up making my code work:
endpoint_api_url="https://abcd.abcd.com/v7/analytics/api/v1/asset/download"
auth_server_url = "https://abcd.abcd.com/v6/authentication/oauth2/token"
client_id = 'abcd'
client_secret='abcd'
token_req_payload = {'grant_type': 'client_credentials'}
token_response = requests.post(auth_server_url,
data=token_req_payload, verify=False, allow_redirects=False,
auth=(client_id, client_secret))
print(token_response.status_code)
if token_response.status_code ==200:
print("Successfuly obtained a new token")
print(token_response.text)
tokens = json.loads(token_response.text)
token = tokens['access_token']
print(token)
else:
print("Failed to obtain token from the OAuth 2.0 server", file=sys.stderr)
sys.exit(1)
params = {"limit":"100", "fromDateTime":"2022-01-01T01:00","toDateTime":"2022-06-01T01:00" }
api_call_headers = {'Authorization': 'Bearer ' + token}
api_call_response = requests.get(endpoint_api_url, headers=api_call_headers, params=params, verify=False)
print(api_call_response.text)

Related

Getting "unsupported_grant_type" when trying to refresh xero API token using python

Getting "unsupported_grant_type" when trying to refresh token using python
Hi,
I've been trying to get a new access token & refresh token using an existing refresh token that I have. I am following the documentation as stated on the website https://developer.xero.com/documentation/oauth2/auth-flow but I keep getting an error saying "unsupported_grant_type" although I do define grant_type = refresh_token. Here's my code, any help would be greatly appreciated.
import json
from base64 import b64encode
client_id = xxx
client_secret = xxx
RefreshToken = xxx
b64_id_secret = b64encode(client_id + ':' + client_secret)
def XeroRefreshToken(refresh_token):
token_refresh_url = 'https://identity.xero.com/connect/token'
response = requests.post(token_refresh_url,
headers = {
'Authorization' : 'Basic ' + b64_id_secret,
'Content-Type': 'application/x-www-form-urlencoded'
},
data = {
'grant_type' : 'refresh_token',
'refresh_token' : refresh_token
})
json_response = response.json()
print(json_response)
new_refresh_token = json_response['refresh_token']
XeroRefreshToken(RefreshToken)

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"}

missing keyword parameter is clearly included in api call

I'm trying to set up a basic API call to Amadeus. All the correct parameters are included and I'm grabbing a fresh token for each call.
It's a React/Flask application.
Here's my endpoint in app/routes.py:
#app.route('/search', methods=['GET'])
#cross_origin(origin='*')
def get_flights():
api_key = os.environ.get('amadeus_api_key', None)
api_secret = os.environ.get('amadeus_api_secret', None)
# first, you must get an access token using your Amadeus credentials
token_request = requests.post(
'https://test.api.amadeus.com/v1/security/oauth2/token',
data = {
'grant_type': 'client_credentials',
'client_id': api_key,
'client_secret': api_secret
}
)
token = token_request.json()['access_token']
bearer = 'Bearer {}'.format(token)
locations = requests.get(
'https://test.api.amadeus.com/v1/reference-data/locations',
headers = {
'Authorization': bearer
},
data = {
'subType': 'AIRPORT',
'keyword': 'BOS'
}
)
print(locations.json())
# example:
# https://test.api.amadeus.com/v1/reference-data/locations
# ?subType=AIRPORT&keyword=BOS
return jsonify({'token': token})
Here's the error:
{'errors': [{'status': 400, 'code': 32171, 'title': 'MANDATORY DATA MISSING', 'detail': 'Missing mandatory query parameter', 'source': {'parameter': 'keyword'}}]}
As you can see in the /search endpoint, the keyword parameter is clearly included.
What gives? Am I missing something?
The request to get the locations is not correctly built as it is sending subType and keyword as body instead of query parameters. According to requests documentation, you need to use params:
locations = requests.get(
'https://test.api.amadeus.com/v1/reference-data/locations',
headers = {
'Authorization': bearer
},
params = {
'subType': 'AIRPORT',
'keyword': 'BOS'
}
)

Unable to generate OAuth 2.0 Access Token from Office365 via JavaScript

I'm trying to pull an access token from Office365's /token identity platform endpoint via OAuth 2.0 client credentials grant flow. I have my app registered, the client ID & secret, etc...
I can make the POST request in Postman and receive the access token without issue:
However, when I try the POST request via JavaScript (by way of Google Apps Script), I receive an error message: AADSTS900144: The request body must contain the following parameter: 'grant_type'
I've already Google'd this error and found a bunch of different solutions, and have tried implementing them to no avail. I imagine this has to do with the URL encoding, but cannot figure it out.
Code:
function getO365() {
// POST Request (To get Access Token)
var tenantID = 'longstringhere'
var appID = 'longstringhere'
var appSecret = 'longstringhere'
var graphScore = 'https://graph.microsoft.com/.default'
var url = 'https://login.microsoftonline.com/' + tenantID + '/oauth2/v2.0/token'
var data = {
'client_id': appID,
'scope': graphScore,
'client_secret': appSecret,
'grant_type': 'client_credentials'
};
var postOptions = {
'method': 'POST',
'headers': {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
'body': data,
'redirect': 'follow'
};
var authToken = UrlFetchApp.fetch(url, postOptions);
}
The only real difference between my code and the JavaScript Fetch code I pulled off of Postman is:
var urlencoded = new URLSearchParams();
urlencoded.append("client_id", "longstringhere");
urlencoded.append("scope", "https://graph.microsoft.com/.default");
urlencoded.append("client_secret", "longstringhere");
urlencoded.append("grant_type", "client_credentials");
When I try to use URLSearchParams in Google Apps Script, I keep getting this error: ReferenceError: URLSearchParams is not defined
Any ideas? Thanks in advance!
This was resolved by changing 'body' to 'payload' for UrlFetchApp per the documentation. Edited code to reflect the change. Credit to #TheMaster for pointing out my mistake.
'payload': data,//from 'body': data,

Can't grant permissions for MS Asure graph API client app to fetch data about ManagedDevices. How to overcome?

I have registered a new app, copied tenant, client_id, and client_secret. I can access https://graph.microsoft.com/v1.0 with Bearer, and access token - works fine. But I can't get anything else. Tried to grant scopes to this app - w/o luck.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pprint
import adal
import requests
pp = pprint.PrettyPrinter(indent=4).pprint
tenant = "<>"
client_id = "<>"
client_secret = "<>"
authority = "https://login.microsoftonline.com/" + tenant
RESOURCE = "https://graph.microsoft.com"
context = adal.AuthenticationContext(authority)
# Use this for Client Credentials
token = context.acquire_token_with_client_credentials(
RESOURCE,
client_id,
client_secret
)
graph_api_endpoint = 'https://graph.microsoft.com/v1.0{0}'
# /me only works with ROPC, for Client Credentials you'll need /<UsersObjectId/
request_url = graph_api_endpoint.format('/Management/managedDevices')
#request_url = graph_api_endpoint.format('/me')
headers = {
'User-Agent' : 'python_tutorial/1.0',
'Authorization' : 'Bearer {0}'.format(token["accessToken"]),
'Accept' : 'application/json',
'Content-Type' : 'application/json'
}
response = requests.get(url = request_url, headers = headers)
pp(response.json())
Here is the error from HTTP reply from the API
{ 'error': { 'code': 'UnknownError',
'innerError': { 'date': '2020-03-15T06:57:54',
'request-id': 'f011ca02-f8c6-4bcb-90a2-9decbed2cfce'},
'message': '{"ErrorCode":"Unauthorized","Message":"{\\r\\n '
'\\"_version\\": 3,\\r\\n \\"Message\\": \\"An '
'error has occurred - Operation ID (for customer '
'support): 00000000-0000-0000-0000-000000000000 - '
'Activity ID: f011ca02-f8c6-4bcb-90a2-9decbed2cfce '
'- Url: '
'https://fef.amsua0402.manage.microsoft.com/DeviceFE/StatelessDeviceFEService/deviceManagement/managedDevices?api-version=2018-05-24\\",\\r\\n '
'\\"CustomApiErrorPhrase\\": \\"\\",\\r\\n '
'\\"RetryAfter\\": null,\\r\\n '
'\\"ErrorSourceService\\": \\"\\",\\r\\n '
'\\"HttpHeaders\\": '
'\\"{\\\\\\"WWW-Authenticate\\\\\\":\\\\\\"Bearer '
'realm=\\\\\\\\\\\\\\"urn:intune:service,c3998d6e-2e37-4c56-87b5-7b444ee1cb26,f0f3c450-59bf-4f0d-b1b2-0ef84ddfe3c7\\\\\\\\\\\\\\"\\\\\\"}\\"\\r\\n}","Target":null,"Details":null,"InnerError":null,"InstanceAnnotations":[]}'}}
You were using client credential flow which request an access token with application permissions.
However, managed device apis are not supported with application permissions.
Reference:
Delegated permissions and Application permissions