mirror of
https://github.com/gradio-app/gradio.git
synced 2025-03-13 11:57:29 +08:00
Fix internal server error in HF OAuth workflow (#8000)
* Fix internal server error in HF OAuth workflow * add changeset * finally working * add changeset * add changeset --------- Co-authored-by: gradio-pr-bot <gradio-pr-bot@users.noreply.github.com> Co-authored-by: Abubakar Abid <abubakar@huggingface.co>
This commit is contained in:
parent
f17d1a0a6f
commit
a0c2848ab5
5
.changeset/many-symbols-arrive.md
Normal file
5
.changeset/many-symbols-arrive.md
Normal file
@ -0,0 +1,5 @@
|
||||
---
|
||||
"gradio": patch
|
||||
---
|
||||
|
||||
feat:Fix internal server error in HF OAuth workflow
|
@ -53,6 +53,7 @@ def attach_oauth(app: fastapi.FastAPI):
|
||||
def _add_oauth_routes(app: fastapi.FastAPI) -> None:
|
||||
"""Add OAuth routes to the FastAPI app (login, callback handler and logout)."""
|
||||
try:
|
||||
from authlib.integrations.base_client.errors import MismatchingStateError
|
||||
from authlib.integrations.starlette_client import OAuth
|
||||
except ImportError as e:
|
||||
raise ImportError(
|
||||
@ -95,7 +96,29 @@ def _add_oauth_routes(app: fastapi.FastAPI) -> None:
|
||||
@app.get("/login/callback")
|
||||
async def oauth_redirect_callback(request: fastapi.Request) -> RedirectResponse:
|
||||
"""Endpoint that handles the OAuth callback."""
|
||||
oauth_info = await oauth.huggingface.authorize_access_token(request) # type: ignore
|
||||
try:
|
||||
oauth_info = await oauth.huggingface.authorize_access_token(request) # type: ignore
|
||||
except MismatchingStateError:
|
||||
# If the state mismatch, it is very likely that the cookie is corrupted.
|
||||
# There is a bug reported in authlib that causes the token to grow indefinitely if the user tries to login
|
||||
# repeatedly. Since cookies cannot get bigger than 4kb, the token will be truncated at some point - hence
|
||||
# losing the state. A workaround is to delete the cookie and redirect the user to the login page again.
|
||||
# See https://github.com/lepture/authlib/issues/622 for more details.
|
||||
login_uri = "/login/huggingface"
|
||||
if "_target_url" in request.query_params:
|
||||
login_uri += (
|
||||
"?"
|
||||
+ urllib.parse.urlencode( # Keep same _target_url as before
|
||||
{"_target_url": request.query_params["_target_url"]}
|
||||
)
|
||||
)
|
||||
for key in list(request.session.keys()):
|
||||
# Delete all keys that are related to the OAuth state
|
||||
if key.startswith("_state_huggingface"):
|
||||
request.session.pop(key)
|
||||
return RedirectResponse(login_uri)
|
||||
|
||||
# OAuth login worked => store the user info in the session and redirect
|
||||
request.session["oauth_info"] = oauth_info
|
||||
return _redirect_to_target(request)
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user