Hi,
I have created project using fastapi project generator (postgres) and now I would like to implement
client in python. However when I try to implement login and get access_token I am getting error.
import os
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
first_superuser = ''
first_superuser_password = ''
REDIRECT_URI = "http://localhost/api/v1/login/access-token"
client = BackendApplicationClient(client_id=first_superuser)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url=REDIRECT_URI,username=first_superuser,
password=first_superuser_password)
The error I am getting back is:
File "/home/radekl/anaconda3/lib/python3.7/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 435, in validate_token_parameters
raise MissingTokenError(description="Missing access token parameter.")
oauthlib.oauth2.rfc6749.errors.MissingTokenError: (missing_token) Missing access token parameter.
I have ask on fastapi gitter and I have search on google but I can not get it work.
Could you please point me to any direction where I can find answear?
Maybe I can use different way to authorize?
And thanks a lot for great library!
I do not know if this is best way how to obtain token but this code works:
import requests
oauth_url = 'http://localhost/api/v1/login/access-token'
data = {
'grant_type': '',
'username': 'some_username',
'password': 'some_password',
'scope': '',
'client_id': '',
'client_secret': ''
}
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
}
response = requests.post(oauth_url, data=data, headers=headers)
response = response.json()
Yep, you found it! 馃殌 That's a way to do it.
You don't need to specify the headers
. When you use data=data
in requests it automatically sends it as form data (if you were sending JSON you would use json=data
).
Now, if your API is expected to be used by other apps you might want to provide another way to generate access tokens, maybe long lived ones, and store them with your client app, instead of putting there your username and password.
Thanks for clarification and for the hint about providing another way to generate access tokens! Something I will definitely try to implement. Not sure how yet :)
However fastapi rocks and the project generators is fantastic tool! Thanks for sharing that and you great work!
Most helpful comment
Thanks for clarification and for the hint about providing another way to generate access tokens! Something I will definitely try to implement. Not sure how yet :)
However fastapi rocks and the project generators is fantastic tool! Thanks for sharing that and you great work!