cat*_*hyk 5 python authlib starlette fastapi
我是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()
Run Code Online (Sandbox Code Playgroud)
我想获取帐户信息。因此,进一步的步骤将是:
GET /login我正在授予使用我的帐户的权限,并将被重定向回我的服务。
GET /auth?oauth_params1=foo&oauth_params2=bar将从令牌提供商获取令牌。我知道我错误地认为该令牌会以某种方式保存在某个地方。
GET /account我期望使用 OAuth 客户端可以发送之前获取的令牌。但是,我收到下一个错误:
authlib.integrations.base_client.errors.MissingTokenError: missing_token:
Run Code Online (Sandbox Code Playgroud)
我也知道我应该提供这样的令牌:
oauth.some_service.get(account_url, token=previously_fetched_token)
Run Code Online (Sandbox Code Playgroud)
但是,我不想每次都询问some-service我想要重用令牌的令牌。怎么做?
我错了,这个问题是范围的一部分吗authlib?我应该寻找缓存或数据库机制的解决方案吗?
ps:我也是初学者FastAPI...
ted*_*ivm -1
这token是一个具有多个值的对象 -
{
"oauth_token": "TOKEN ID",
"oauth_token_secret": "SECRET TOKEN",
"user_id": "USER ID",
"screen_name": "USER SCREEN NAME"
}
Run Code Online (Sandbox Code Playgroud)
你有几个选择——
| 归档时间: |
|
| 查看次数: |
898 次 |
| 最近记录: |