Anonymous
Токен аутентификации FASTAPI не появляется на бренде
Сообщение
Anonymous » 26 янв 2025, 21:15
Я использую Google OAuth для аутентификации в своем приложении. Но файл cookie не отображается в файлах cookie браузера. Я возвращаю ответ перенаправления из обратного вызова и устанавливаю в него файл cookie. Мне бы хотелось узнать о каком-либо другом безопасном способе использования токена во внешнем интерфейсе.
Код: Выделить всё
@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)}")
Я создал объект ответа для ссылки перенаправления и прикрепил к нему токен. Но он по-прежнему не отображается в интерфейсе.
Подробнее здесь:
https://stackoverflow.com/questions/793 ... e-frontend
1737915359
Anonymous
Я использую Google OAuth для аутентификации в своем приложении. Но файл cookie не отображается в файлах cookie браузера. Я возвращаю ответ перенаправления из обратного вызова и устанавливаю в него файл cookie. Мне бы хотелось узнать о каком-либо другом безопасном способе использования токена во внешнем интерфейсе. [code]@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] Я создал объект ответа для ссылки перенаправления и прикрепил к нему токен. Но он по-прежнему не отображается в интерфейсе. Подробнее здесь: [url]https://stackoverflow.com/questions/79389052/fastpi-authentication-token-in-not-appearing-in-the-frontend[/url]