【发布时间】:2021-12-15 19:11:13
【问题描述】:
我是 authlib 的初学者,并试图理解它的概念。
我试图了解,如何使用authlib 保存和重复使用获取的令牌。
我创建了一个小的FastAPI 项目:
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()
我想获取帐户信息。因此,进一步的步骤将是:
GET /login
我正在授予使用我的帐户的权限,并将被重定向回我的服务。
GET /auth?oauth_params1=foo&oauth_params2=bar
将从令牌提供者处获取令牌。我知道我错误地认为该令牌会以某种方式保存在某个地方。
GET /account
我期望使用 OAuth 客户端可以发送以前获取的令牌。但是,我收到下一个错误:
authlib.integrations.base_client.errors.MissingTokenError: missing_token:
我也知道我应该提供这样的令牌:
oauth.some_service.get(account_url, token=previously_fetched_token)
但是,我不想每次都从some-service 询问令牌,我想重用令牌。该怎么做?
我错了,这个问题是authlib 范围的一部分吗?我应该找到缓存或数据库机制的解决方案吗?
p.s.:我也是FastAPI 的初学者...
【问题讨论】:
-
嘿@catscoolzhyk 你有进步吗?
标签: python fastapi authlib starlette