Using easyauth with FastAPI and requests #75
-
Hi there! I'd like to control a device by using a REST-API. However, I'd like restrict the access. So far, I have written a python script based on FastAPI which provides all the routes that resemble the functions of my device (e.g. turn something on/off). I also added the functionality provided by easyauth to authenticate with a separate easyauth-server (i.e. there is a separate script to run the authentication server). I happily used the docs here. This works well, as I can see from the build in "docs"-route, both for the auth-server and the REST-API. Now, I'd like to access the above not by use of a web browser but from within another python script that uses the requests package (or something else suitable). Unfortunately, I couldn't find an example nor some documentation which points me into some direction. Someone here, who can help, please? Thanks a lot in advance |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Hey @w-markus , in order to access a protected endpoint, a script will need to attach an auth header containing a generated bearer token. import os
import requests
username = 'admin' # or other created user
password = os.environ['PW_FROM_ENV']
# required header for using username / password to request a token
headers = {'accept': 'application/json', 'content-type': 'application/x-www-form-urlencoded'}
token_request = requests.post(
'http://my-token_server/auth/token',
headers=headers,
data=f'username={username}&password={password}'
)
token = token_request['access_token'] # you could use service account token instead
headers = {'Authorization': f'Bearer {token}'}
# use headers for accessing any other protected endpoint
r = requests.get('http://other-service/api/v1/data', headers=headers) You can replace requesting a token if you create service account & generate a token for the service account and use the same way as |
Beta Was this translation helpful? Give feedback.
-
Typically |
Beta Was this translation helpful? Give feedback.
Hey @w-markus , in order to access a protected endpoint, a script will need to attach an auth header containing a generated bearer token.