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
Related
Problem :
I need to get a list of certificates of apps registered under Azure AD and renew the ones which are expiring.
I was able to get the apps related details through Microsoft Graph API > applications. But, the issue is the bearer token refreshes every time in 1 hr. Since I want this task to be automated, I need to create a fresh token always.
I got some reference of Azure SDK for identity-based authentication but the package function is returning a credential, not a token (bearer token) to be used inside the rest API header Authorization
Code:
from azure.identity import DefaultAzureCredential
default_credential = DefaultAzureCredential()
References:
Azure api or sdk to get list of app registrations and the certificates associated with them
Ok after a lot of debugging and surfing the internet, I was able to find the RestAPI way to get the bearer token.
data = {
"client_id":"add your client id",
"scope": "add scope ex: User.read Directory.read.All",
"grant_type": "password", [don't modify this one since you are providing the password]
"username": "your username",
"password": "your password",
"client_secret": "client secret"
}
headers = {
"Host": "login.microsoftonline.com",
"Content-Type": "application/x-www-form-urlencoded"
}
data = requests.post(f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token', data=data, headers=headers)
You will receive a json consisting of access token and related details.
Do remember to provide the permissions in the azure portal> Azure AD > app registrations > your app > API permissions (grant consent)
: )
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)
This is a bit of a newbie Q.
I'm using Python 3.6
I am trying to use the domain realestate api to write a scraper that collects data of houses/apartments for sale in my area, but i am having trouble getting the post request to work. I have registered and retrieved my client_id and secret_id for the authentication. The post request returns a status_code of 400
response = requests.post('https://auth.domain.com.au/v1/connect/token',
data = {'client_id':client_id,
"client_secret":client_secret,
"grant_type":"client_credentials",
"scope":"api_agencies_read api_listings_read",
"Content-Type":"application/json"})
token=response.json()
access_token=token["access_token"]
search_parameters = {
"listingType": "Sale",
"locations": [
{
"state": "NSW",
"suburb": "Balgowlah",
"postcode": 2093,
"includeSurroundingSuburbs": True
}
]
}
url = "https://api.domain.com.au/v1/listings/residential/_search"
auth = {"Authorization":"Bearer "+access_token}
request = requests.post(url, data=search_parameters, headers=auth)
details=request.json()
I know my authentication is correct, because i can use the Live API on the website to test the same request (i had to select the client, secret id and the project to allow direct access), and i get a valid access token from the code above.
access_token:
{'access_token': 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
'expires_in': 43200,
'token_type': 'Bearer'}
request.json():
{'errors': {'parameters': ['Undefined error.']},
'message': 'The request is invalid.'}
I've been able to implement the notebook from this post. So i can be sure my client and secret ids are connected to the domain project.
#furas had the solution:
look at the example closer :)
The example uses "Content-Type":"text/json" but you use "application/json" instead of "text/json"
I'm using the Django Rest Framework with django-oauth-toolkit, When I make a request on POSTMAN, with this body it works fine,
{
"username":"username",
"password":"password",
"client_id":"something",
"client_secret":"somethingelse",
"grant_type":"password"
}
When I make the same request using requests, I get
unsupported_grant_type
This is my request code,
data = {"username": username,
"password": password,
"client_id": client_id,
"client_secret": client_secret,
"grant_type": "password"}
r = requests.post(url, data=data)
I'm using the string "password" as grant_type. It works in Postman, just doesn't work in code.
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