I'm following the Get access without a user guide to write a Python script that will call Microsoft Graph.
This script will be scheduled from cron so it cannot get admin consent (therefore authorize using Client Credentials). I am able to successfully obtain a token using this call:
request_url = "https://login.microsoftonline.com/mytenant.onmicrosoft.com/oauth2/v2.0/token"
data = {
'Host' : 'login.microsoftonline.com',
'Content-Type' : 'application/x-www-form-urlencoded',
'client_id' : 'my-client-id-1234',
'scope' : 'https://graph.microsoft.com/.default',
'client_secret' : client_secret,
'grant_type' : 'client_credentials'
}
response = requests.post(url = request_url, data = data)
I then try to get a user listing with this call, using the valid token:
request_url = "https://graph.microsoft.com/v1.0/users"
headers = {
'Authorization' : 'Bearer ' + token,
'Host' : 'graph.microsoft.com'
}
response = requests.get(url = request_url, headers = headers)
The problem is that I get an Authorization_IdentityNotFound error:
<Response [401]>
{
"error": {
"code": "Authorization_IdentityNotFound",
"message": "The identity of the calling application could not be established.",
"innerError": {
"request-id": "2257f532-abc4-4465-b19f-f33541787e76",
"date": "2018-03-27T19:11:07"
}
}
}
These are the permissions I've selected:
Any idea how to fix this error?
For others running into this issue, I was also getting this error until found out the documentation omits a very important caveat:
For client credentials, if the app belongs to a work or school (organization) context then for https://login.microsoftonline.com/common/oauth2/token replace common with a tenantId or domain name
See
Authorization_IdentityNotFound on Microsoft Graph API request
First things first, you can go ahead an remove all those Delegated Permission scopes. If you're using the Client Credentials Grant, you will only be using Application Permission scopes.
Second, you need to execute the Admin Consent flow before you can use Client Credentials. This is done by having a Global Admin from the tenant authenticate and accept your scope request:
https://login.microsoftonline.com/common/adminconsent?client_id=[APPLICATION ID]&redirect_uri=[REDIRECT URI]
You can read more about Admin Consent here: v2 Endpoint and Admin Consent
Related
I'm trying to create a python script which takes a (.csv with access tokens and a file) as input and uploads that file to multiple google drives whose access tokens are in that csv
but after sometime access tokens get expired and I have to get them again...just saw there's something called refresh and it refreshes access token
Is it possible to do this from python script, please explain.
Do refresh token expire?
import json
import requests
import pandas as pd
headers = {}
para = {
"name": "update",
}
files = {
'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),
'file': open("./update.txt", "rb")
}
tokens = pd.read_csv('tokens.csv')
for i in tokens.token:
headers={"Authorization": i}
r = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
headers=headers,
files=files
)
print(r.text)
In order to be able to get a new access_token programmatically using a refresh_token, you must have set access_type to offline when redirecting the user to Google's OAuth 2.0 server.
If you did that, you can get a new access_token if you do the following POST request to https://oauth2.googleapis.com/token:
POST /token HTTP/1.1
Host: oauth2.googleapis.com
Content-Type: application/x-www-form-urlencoded
client_id=your_client_id&
client_secret=your_client_secret&
refresh_token=refresh_token&
grant_type=refresh_token
The corresponding response would be something like:
{
"access_token": "1/fFAGRNJru1FTz70BzhT3Zg",
"expires_in": 3920,
"scope": "https://www.googleapis.com/auth/drive",
"token_type": "Bearer"
}
Note:
You can find code snippets for several languages in the reference I provide below, including Python, but considering you are not using the Python library, I think the HTTP/REST snippet I provided might be more useful in your situation.
Reference:
Refreshing an access token (offline access)
I'm new to working with APIs. I'm trying to create a script that will output the tracks of a public playlist from Spotify. I have hit a roadblock at an early stage: I'm unsure how exactly to format my GET request to retrieve the tracks of the playlist in question and where I put the OAuth access token. My current attempt returns a 401 status code.
What I've done so far:
I have created an App on the Spotify Developers website dashboard.
I have saved client_id and client_secret from the dashboard into a script ("spotifysecrets.py").
I have run the following code in my main script:
import requests
from spotifysecrets import client_id as cid, client_secret as cs
AUTH_URL = "https://accounts.spotify.com/api/token"
token_req = requests.post(AUTH_URL, {
"grant_type": "client_credentials",
"client_id": cid,
"client_secret": cs
})
access_token = token_req.json()["access_token"]
Everything appears to have worked fine so far. The problem occurs in the next step.
Having obtained the token, I am getting a 401 error when trying to make my tracks request. The code I have written is as follows:
pl_id = "…" # I have elided the actual playlist ID for the purposes of this question
tracks = "https://api.spotify.com/v1/playlists/{}/tracks".format(pl_id)
songs_req = requests.get(tracks, {
"Authorization": "Basic {}".format(access_token)
})
Edit
I have tried using
songs_req = requests.get(tracks, headers={
"Authorization": "Basic {}".format(access_token)
})
instead but this gives a 400 error.
I looked into the api and I believe you have a syntax error:
songs_req = requests.get(tracks, {
"Authorization": "Basic {}".format(access_token)
})
should be:
songs_req = requests.get(tracks, {
"Authorization": "Bearer {}".format(access_token)
})
I am deploying a Google Cloud Function from another Cloud Function with Python. See my code below:
import requests
import json
def make_func(request):
# Get the access token from the metadata server
metadata_server_token_url = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token?scopes=https://www.googleapis.com/auth/cloud-platform'
token_request_headers = {'Metadata-Flavor': 'Google'}
token_response = requests.get(metadata_server_token_url, headers=token_request_headers)
token_response_decoded = token_response.content.decode("utf-8")
jwt = json.loads(token_response_decoded)['access_token']
# Use the api to create the function
response = requests.post('https://cloudfunctions.googleapis.com/v1/projects/myproject/locations/us-central1/functions',
json={"name":"projects/my-project/locations/us-central1/functions/funct","runtime":"python37","sourceArchiveUrl":"gs://bucket/main.zip","entryPoint":"hello_world","httpsTrigger": {} },
headers={'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer {}'.format(jwt)} )
if response:
return 'Success! Function Created'
else:
return str(response.json())
However this function does not have "allow unauthenticated" on automatically. Thus, no requests from outside are allowed. How can I change my Python code to add this functionality when deploying the new function?
Thanks
You'll need to additionally give the allUsers member the Cloud Functions Invoker role:
from googleapiclient.discovery import build
service = build('cloudfunctions', 'v1')
project_id = ...
location_id = ...
function_id = ...
resource = f'projects/{project_id}/locations/{location_id}/functions/{function_id}'
set_iam_policy_request_body = {
'policy': {
"bindings": [
{
"role": "roles/cloudfunctions.invoker",
"members": ["allUsers"],
},
],
},
}
request = service.projects().locations().functions().setIamPolicy(
resource=resource,
body=set_iam_policy_request_body,
)
response = request.execute()
print(response)
This uses the google-api-python-client package.
In addition of Dustin answer, you have to know that the --allow-unauthenticated is for developer convenience. Under the hood it perform 2 things
Deploy your function in private mode
Add allUsers as member with Cloudfunction.invoker role
gcloud functions add-iam-policy-binding --member=allUsers --role=roles/cloudfunctions.invoker function-1
So, indeed, use the google-cloud-iam library for doing this.
In addition, your current code don't work because you use an access token to reach Cloud Function.
Indeed, you have an authorized error (401) -> You present an authorization header, but it's not authorize.
Without the header, you get a 403 error -> unauthenticated.
Anyway, you need to have a signed identity token. You have description and python code snippet here
currently I am using eBay Trading API with Python. Thanks to: https://github.com/timotheus/ebaysdk-python
I used https://github.com/luke-dixon/django-ebay-accounts to get tokens for user.
Now, I would like to use Restful API (https://developer.ebay.com/docs#Acc). I don't think I can use tokens I have already. So, I managed thanks to Getting an Ebay OAuth Token get one. But I think I missing something, because during the process I cannot include info for user (name/password), so, for example https://api.ebay.com/sell/fulfillment/v1/order?limit=10 returns:
{
"errors": [{
"errorId": 1100,
"domain": "ACCESS",
"category": "REQUEST",
"message": "Access denied",
"longMessage": "Insufficient permissions to fulfill the request."
}]
}
Any idea how can I get a token for the user?
Just snippet of code to make things more clear:
AppSettings = {
'app_id': EBAY_PRODUCTION_APPID,
'app_secret': EBAY_PRODUCTION_CERTID,
'dev_id': EBAY_PRODUCTION_DEVID,
'ruName': EBAY_PRODUCTION_RU_NAME
}
authHeaderData = AppSettings['app_id'] + ':' + AppSettings['app_secret']
encodedAuthHeader = base64.b64encode(authHeaderData.encode())
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic ".encode() + encodedAuthHeader
}
body = {
"grant_type": "client_credentials",
"redirect_uri": settings.EBAY_PRODUCTION_RU_NAME,
"scope": "https://api.ebay.com/oauth/api_scope"
}
data = urllib.parse.urlencode(body)
tokenURL = "https://api.ebay.com/identity/v1/oauth2/token"
response = requests.post(tokenURL, headers=headers, data=body)
authDict = response.json()
So the request to run I need is:
r = requests.get("https://api.ebay.com/sell/fulfillment/v1/order?limit=10",
headers={"Authorization": "{}".format(authDict['access_token']),
"Content-Type": "application/json",
"X-EBAY-C-MARKETPLACE-ID": "EBAY_UK",
"Accept": "application/json"
})
According to this, I believe you are supposed to use the following authorization header:
headers['Authorization'] = "Bearer " + USER_ACCESS_TOKEN
Where the USER_ACCESS_TOKEN is the massive token generated on this page.
It looks something like this:
'v^1.1#i^1#p^3#f^0#I^3#r^0#t^ ...
...
...
...
... bfxr8BJtphi2M/oo2xpYo2hiMWxmZt4fVzS7qe2tMXUSAAA='
The Authorization you are using is for requests that aren't linked to a specific user account (search results, meta data for items, etc.). To make requests that are for specific users (eg. orders or inventory updates), you have to get their permission via their USER_ACCESS_TOKEN.
If you need help getting the USER_ACCESS_TOKEN let me know and I'll update.
Note that I have been trying to do the same thing that you are doing for about 6 hours now, and still haven't figured it out, so I am not confident in this answer.
Hope this helps. If you do figure it out, you should post an answer so others can too (ie myself xD).
eBay definitely wins the gold metal for worst api docs in the history of api docs...
The API Explore # developer.ebay.com has description of HTTP Headers for each RestFul API. E.G. Fulfillment API - getOrdres:
HTTP Headers
Authorization:Bearer <OAUTH_token>
Accept:application/json
Content-Type:application/json
Sample code:
import requests,json
headers = {
"Authorization": "Bearer Type_Your_Token_here_or_Paste_IF_too_long",
'Accept':'application/json',
'Content-Type':'application/json'
}
EndPoint = "https://api.ebay.com/sell/fulfillment/v1/order?filter=orderfulfillmentstatus:%7BNOT_STARTED|IN_PROGRESS%7D"
response = requests.get(EndPoint,headers = headers)
https://newbedev.com/ebay-oauth-token-and-refresh-tokens has introduced eBay OAuth token much better than eBay.
By the way, "grant_type": "client_credentials" is only valid for clients who can on have one scope. https://api.ebay.com/oauth/api_scope.
A shortcut to get your code run: the refresh token is actually the token you have for standard API, which is valid for 18 months. With a refresh token, you can get token without getting the annoying "authorization code" via user consent.
In short, please use refresh token to get user access token for the restful API.
Hope the above helps.
I am trying to generate acces token from refresh token in django.
I am using Oauth2.
I am using oauth2 internal url for generating access token
i.e, 127.0.0.1:8000/o/token/
I am testing this in Rest Console.
My request is:
{ "client_id": "m5JjAzkqOCdH9MC4KV9EAjKuNhdMv2TyNDXgD6T7", "client_secret": "6C495R1BiA0lfXgm7lh0Zvqc6ugB7H6srlwSCLwyVNgoKqK7xGVQbB63Hj97E7fw3tWIgG7tnv9K5nwInaKPaaqSy4FLm8jaBdTPZ8YzlCJMkuiWNbIwc0ltFB7H9cgq",
"username": "lalit198910",
"grant_type": "refresh_token",
"token type" : "Bearer",
"refresh_token": "1svsHogo5tq6UxkiY55iMvMpWnGRsn" }
the error i am getting is:
"error": "unsupported_grant_type"
my content type is :
application/x-www-form-urlencoded
In Custom headers i have :
authorization type: bearer
value :3nKkSW9TEPjusuy2PzKhFxoTkFlqQC(Access token)
I have solved this problem,
I was using RAW BODY to pass my request data instead of using Request Paramters