Я использую Google Oauth для аутентификации в моем приложении. Но печенье не появляется в печенье в браузере. Я возвращаю ответ перенаправления от обратного вызова и устанавливаю в него файл cookie. Я хотел бы знать о любом другом безопасном способе, как к токену на бренде. < /P>
@router.get("/google/login")
async def google_login():
flow = Flow.from_client_secrets_file(
CLIENT_SECRETS_FILE,
scopes=SCOPES,
redirect_uri=settings.google_redirect_uri
)
authorization_url, state = flow.authorization_url(
access_type='offline',
include_granted_scopes='true'
)
return RedirectResponse(authorization_url)
@router.get("/google/callback")
async def google_callback(
code: str,
response: Response,
state: str = None,
session: AsyncSession = Depends(get_session)
):
response.headers['set-auth-cookies'] = 'true'
try:
flow = Flow.from_client_secrets_file(
CLIENT_SECRETS_FILE,
scopes=SCOPES,
redirect_uri=settings.google_redirect_uri
)
# Use the authorization server's response to fetch the OAuth 2.0 tokens
flow.fetch_token(code=code)
# Get the ID token from OAuth2 flow
credentials = flow.credentials
id_info = id_token.verify_oauth2_token(credentials.id_token, requests.Request(), settings.google_client_id)
user: UserCreate = UserCreate(name=id_info.get('name'), email=id_info.get('email'), password="", is_verified=True)
user_auth = AuthenticationService(session, user, google_user=True)
if await user_auth.user_exists() and await user_auth.user_verified():
print("User exists and is verified")
access_token_expires = timedelta(minutes=30)
access_token = create_access_token(data={"sub": user.email}, expires_delta=access_token_expires)
headers = {'Authorization': f'Bearer {access_token}'}
response.set_cookie(
key="access_token",
value=access_token,
httponly=True,
domain='localhost'
)
print("You are in google callback 1")
print(response)
print(response.status_code)
print(response.headers)
# print(response.cookies)
return RedirectResponse(url="http://localhost:5173/auth-success", headers=headers, status_code=302)
elif await user_auth.user_exists() and not await user_auth.user_verified():
print("User exists and is not verified")
await user_auth.set_verified()
access_token_expires = timedelta(minutes=30)
access_token = create_access_token(data={"sub": user.email}, expires_delta=access_token_expires)
headers = {'Authorization': f'Bearer {access_token}'}
response.set_cookie(
key="access_token",
value=access_token,
httponly=True,
domain='localhost'
)
return RedirectResponse(url="http://localhost:5173/auth-success", headers=headers, status_code=302)
else:
print("User does not exist")
await user_auth.create_user()
access_token_expires = timedelta(minutes=30)
access_token = create_access_token(data={"sub": user.email}, expires_delta=access_token_expires)
headers = {'Authorization': f'Bearer {access_token}'}
response.set_cookie(
key="access_token",
value=access_token,
httponly=True,
domain='localhost'
)
return RedirectResponse(url="http://localhost:5173/auth-success", headers=headers, status_code=302)
except Exception as e:
raise HTTPException(status_code=400, detail=f"Invalid id_token: {str(e)}")
< /code>
Я создал объект ответа для ссылки перенаправления и прикрепил к нему токен. Но все же это не появляется на фронте.
Подробнее здесь: https://stackoverflow.com/questions/793 ... e-frontend
Токен аутентификации FastAPI не отображается во внешнем интерфейсе [дубликат] ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение