tenup
tenup

Reputation: 55

FastAPI & Authlib external oauth authentication reuse authlib client

I have trouble understanding how the Authlib middleware works with fastAPI.

I have something working, but I don't think it's the right way to do it.

What I would like is to be able to create a client like in this example.

auhlib client.

From what I understand, the SessionMiddleware is supposed to do all the work and with a client that auto refresh the token and all that.

What I do is store the access_token inside request.session and then read it again when I need it, but it looks like the wrong way to do it.

Here's my code :

import requests
from authlib.integrations.base_client import OAuthError
from authlib.integrations.starlette_client import OAuth
from fastapi import FastAPI
from starlette.requests import Request
from starlette.responses import HTMLResponse, RedirectResponse
from starlette.middleware.sessions import SessionMiddleware

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="some-random-string")
oauth = OAuth()
oauth.register(
    name="oauthprovider",
    client_id="MYCLIENTID",
    client_secret="MYCLIENTSECRET",
    server_metadata_url="https://example.com/.well-known/openid-configuration",
)
@app.get('/login')
async def login(request: Request):
    redirect_uri = "http://localhost:8000/auth/callback"
    return await oauth.oauthprovider.authorize_redirect(request, redirect_uri)
@app.get('/auth/callback')
async def auth(request: Request):
    try:
        token = await oauth.oauthprovider.authorize_access_token(request)
    except OAuthError as error:
        return HTMLResponse(f'<h1>{error.error}</h1>')
    user = token.get('userinfo')
    if user:
        request.session['user'] = dict(user)
        request.session['access_token'] = token.get('access_token')
    return RedirectResponse(url='/docs')
@app.get('/fetchexternalAPI')
async def externalAPI(request: Request):
    headers = { "Authorization": f"Bearer {request.session['access_token']}"}
    res = requests.get(url="https://example.com/api", headers=headers)
    return res.json()

I would like to do something like:

oauth.oauthprovider.get("https://example.com"),

so I use the client correctly (depending on the current user obviously) and the token would be refreshed I guess?

The only example I found doesn't use this client... example

Upvotes: 0

Views: 384

Answers (0)

Related Questions