@@ -56,7 +56,10 @@ async def oauth2_github():
5656``` python
5757@app.get (" /oauth2/github/callback" )
5858async def oauth2_github_callback (
59- oauth_result : Annotated[FastAPIOAuth20, Depends(github_oauth)]
59+ oauth_result : Annotated[
60+ FastAPIOAuth20,
61+ Depends(github_oauth),
62+ ],
6063):
6164 """ 处理 GitHub OAuth 回调"""
6265 token_data, state = oauth_result
@@ -131,46 +134,37 @@ async def oauth2_authorize_callback_error_handler(request: Request, exc: OAuth20
131134``` python
132135from typing import Annotated
133136
134- from fastapi import FastAPI, Depends, HTTPException
137+ from fastapi import FastAPI, Depends
135138from fastapi.responses import RedirectResponse
136- from fastapi_oauth20 import GitHubOAuth20, FastAPIOAuth20
137- from fastapi_oauth20 import OAuth20AuthorizeCallbackError
138139
139- import secrets
140+ from fastapi_oauth20 import GitHubOAuth20, FastAPIOAuth20
140141
141142app = FastAPI()
142143
143- # 初始化客户端
144- github_client = GitHubOAuth20(
145- client_id = " your_client_id" ,
146- client_secret = " your_client_secret"
147- )
144+ redirect_uri = " http://localhost:8000/auth/github/callback"
148145
149- # 创建依赖
150- github_oauth = FastAPIOAuth20(
151- client = github_client,
152- redirect_uri = " http://localhost:8000/auth/github/callback"
146+ github_client = GitHubOAuth20(
147+ client_id = " your_github_client_id" ,
148+ client_secret = " your_github_client_secret"
153149)
154150
155151
156- @app.get (" /oauth2/github" )
157- async def oauth2_github ():
158- """ GitHub 授权入口"""
159- state = secrets.token_urlsafe(32 )
160- auth_url = await github_client.get_authorization_url(
161- redirect_uri = " http://localhost:8000/auth/github/callback" ,
162- state = state
163- )
152+ @app.get (" /auth/github" )
153+ async def github_auth ():
154+ auth_url = await github_client.get_authorization_url(redirect_uri = redirect_uri)
164155 return RedirectResponse(url = auth_url)
165156
166157
167- @app.get (" /oauth2/github/callback" )
168- async def oauth2_github_callback (
169- oauth_result : Annotated[FastAPIOAuth20, Depends(github_oauth)]
158+ @app.get (" /auth/github/callback" )
159+ async def github_callback (
160+ oauth2 : Annotated[
161+ FastAPIOAuth20,
162+ Depends(FastAPIOAuth20(github_client, redirect_uri = redirect_uri)),
163+ ],
170164):
171- """ GitHub 授权回调 """
172- token_data, state = oauth_result
173- user_info = await github_client.get_userinfo(token_data[ " access_token" ] )
165+ token_data, state = oauth2
166+ access_token = token_data[ ' access_token ' ]
167+ user_info = await github_client.get_userinfo(access_token)
174168 return {" user" : user_info}
175169
176170
0 commit comments