OAuth 2.0 的验证与授权中间件实现
from fastapi import FastAPI, Depends
from starlette.requests import Request
from starlette.responses import JSONResponse
from authlib.integrations.starlette_oauth2 import OAuth2Callback, OAuth2PasswordBearer
from authlib.oauth2.rfc6749 import InvalidClientError, TokenExpiredError
app = FastAPI()
# 假设这是你的OAuth2客户端配置
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="https://example.com/oauth2/token")
@app.exception_handler(InvalidClientError)
async def invalid_client_exception_handler(request: Request, exc: InvalidClientError):
return JSONResponse({"detail": exc.description}, status_code=401)
@app.exception_handler(TokenExpiredError)
async def token_expired_exception_handler(request: Request, exc: TokenExpiredError):
return JSONResponse({"detail": "Token expired"}, status_code=401)
@app.get("/items/")
async def read_items(token: str = Depends(oauth2_scheme)):
return {"token": token}
@app.get("/login/")
async def login():
return {"msg": "Login using OAuth2"}
@app.get("/callback/")
async def callback(request: Request):
return await OAuth2Callback.get_token(request)
这个代码示例展示了如何在FastAPI应用中使用authlib
库来实现OAuth2的验证和授权中间件。它定义了一个oauth2_scheme
,并为InvalidClientError
和TokenExpiredError
异常定义了异常处理器,以便返回更加友好的错误信息。同时,它提供了一个登录页面/login/
和一个回调页面/callback/
,用于处理OAuth2的登录流程和获取令牌。在read_items
路由中,它使用依赖注入来验证访问令牌的有效性。
评论已关闭