I'm very beginner with authlib and trying to understand its concepts.
I try to understand, how can I save and reuse fetched tokens with authlib
.
I created small FastAPI
project:
from fastapi import FastAPI
from starlette.config import Config
from starlette.middleware.sessions import SessionMiddleware
from starlette.requests import Request
from authlib.integrations.starlette_client import OAuth
app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="some-random-secret")
config = Config(".env")
oauth = OAuth(config)
oauth.register(
name="some_service",
client_id="client_id",
client_secret="client_secret",
authorize_url="https://some-service.com/auth",
access_token_url="https://some-service.com/token",
client_kwargs={
"token_endpoint_auth_method": "client_secret_post",
},
)
@app.get("/login")
async def login(request: Request):
redirect_uri = "https://myservice.com/auth"
return await oauth.some_service.authorize_redirect(request, redirect_uri)
@app.get("/auth")
async def auth(request: Request):
token = await oauth.some_service.authorize_access_token(request)
# I suppose that I should save somehow token here
return token
@app.get("/account")
async def get_account(request: Request):
account_url = "https://some-service.com/account"
resp = await oauth.some_service.get(account_url)
return resp.json()
I want to get account info. So, further steps will be:
GET /login
I'm giving access to use my account and will be redirected back to my service.
GET /auth?oauth_params1=foo&oauth_params2=bar
There will be fetched tokens from token provider. I know that I'm wrongly supposing that token will somehow saved somewhere.
GET /account
And there I'm expecting that with OAuth client I can send previously fetched token. But, I'm getting next error:
authlib.integrations.base_client.errors.MissingTokenError: missing_token:
I also know that I should provide token like that:
oauth.some_service.get(account_url, token=previously_fetched_token)
But, I don't want to ask every time token from some-service
I want to reuse token. How to do that?
Am I wrong that this issue is the part of authlib
scope? Should I find solution with cache or database mechanisms?
p.s.: I'm really beginner with FastAPI
too...