|
| 1 | +提供的实用程序可简化 FastAPI 中 OAuth2 流程的集成 |
| 2 | + |
| 3 | +## `FastAPIOAuth20` |
| 4 | + |
| 5 | +依赖关系可调用,用于处理授权回调,它读取查询参数并返回访问令牌和状态 |
| 6 | + |
| 7 | +```python |
| 8 | +from fastapi import FastAPI, Depends |
| 9 | +from fastapi_oauth20 import FastAPIOAuth20, LinuxDoOAuth20 |
| 10 | + |
| 11 | +client = LinuxDoOAuth20("CLIENT_ID", "CLIENT_SECRET") |
| 12 | +linuxdo_oauth2_callback = FastAPIOAuth20(client, "oauth2-callback") |
| 13 | + |
| 14 | +app = FastAPI() |
| 15 | + |
| 16 | + |
| 17 | +@app.get("/oauth2-callback", name="oauth-callback") |
| 18 | +async def oauth2_callback(access_token_state=Depends(linuxdo_oauth2_callback)): |
| 19 | + token, state = access_token_state |
| 20 | + # Do something useful |
| 21 | +``` |
| 22 | + |
| 23 | +## 自定义异常 |
| 24 | + |
| 25 | +如果回调逻辑内部发生错误(用户拒绝访问、授权代码无效......),依赖关系将引发 `OAuth20AuthorizeCallbackError` 错误 |
| 26 | + |
| 27 | +它继承自 FastAPI 的 [HTTPException](https://fastapi.tiangolo.com/reference/exceptions/#fastapi.HTTPException),因此默认的 |
| 28 | +FastAPI 异常处理程序会自动对其进行处理。您可以通过为 `OAuth20AuthorizeCallbackError` 实现自己的异常处理程序来自定义此行为 |
| 29 | + |
| 30 | +```python |
| 31 | +from fastapi import FastAPI, Request |
| 32 | +from fastapi.responses import JSONResponse |
| 33 | +from fastapi_oauth20.integrations.fastapi import OAuth20AuthorizeCallbackError |
| 34 | + |
| 35 | +app = FastAPI() |
| 36 | + |
| 37 | + |
| 38 | +@app.exception_handler(OAuth20AuthorizeCallbackError) |
| 39 | +async def oauth2_authorize_callback_error_handler(request: Request, exc: OAuth20AuthorizeCallbackError): |
| 40 | + detail = exc.detail |
| 41 | + status_code = exc.status_code |
| 42 | + return JSONResponse( |
| 43 | + status_code=status_code, |
| 44 | + content={"message": "The OAuth2 callback failed", "detail": detail}, |
| 45 | + ) |
| 46 | +``` |
0 commit comments