Can't authenticate using httpx AsyncClient #1237
-
Hello! I've read a lot of discussions in this repo, but no one worked for me. The problem is very similar to the discussion. Can't auth using htpps.AsyncClient: @pytest.fixture(scope="session")
async def async_client() -> AsyncGenerator[httpx.AsyncClient, None]:
async with httpx.AsyncClient(app=app, base_url="http://127.0.0.1:8000/api/v1", follow_redirects=True) as ac:
yield ac
async def test_add_event(async_client: httpx.AsyncClient):
auth_req = await async_client.post('auth/login',
data={'username': "authed_user", 'password': "authed_user_password"})
cookies = auth_req.headers['set-cookie']
headers = {'Content-Type': 'application/json', 'Authorization': f'token {cookies}', 'cookie': cookies}
response = await async_client.post('/events', json=test_event, headers=headers, cookies=auth_req.cookies)
assert response.status_code == 201
@router.post(
"/",
response_model=schemas.CreatedEventResponseSchema,
status_code=status.HTTP_201_CREATED,
responses={
status.HTTP_400_BAD_REQUEST: {
"model": schemas.EventAlreadyExistsSchema,
"description": "Event already exists"
}
})
async def add_event(event: schemas.NewEventSchema,
session: AsyncSession = Depends(APP_CTX.pg_controller.get_async_session),
user: User = Depends(current_user)):
pass I've tried already everything but all time getting 401 - unathorized. Cookie is coming in the correct format(checked it with swagger client authorize). What am I doing wrong? At the same time |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
I'm not certain the value of An HTTPX Client instance is able to automatically maintain the cookie state across several requests. So if you just do: auth_req = await async_client.post('auth/login', data={'username': "authed_user", 'password': "authed_user_password"})
response = await async_client.post('/events', json=test_event)
assert response.status_code == 201 It should work directly. Please note that the |
Beta Was this translation helpful? Give feedback.
Are you sure you set the cookie secure flag to
False
, as I mentioned in my previous answer?https://github.com/mixa2130/events_registration_api/blob/55d6e8dc9249c12269510510e7b28d7b7eccba42/src/auth/config.py#L12
The default is
True
. My recommendation is to have an environment variable for this so you can easily switch it toFalse
in local and toTrue
in production.The value of
Set-Cookie
contains not only the cookie name and its value, but also the flags likeHttpOnly
,Secure
, etc.The
Cookie
header only expectsName=Value
pairs. So, I'm not sure the server is able to recognize them if they contain the flags. …