arunppsg
arunppsg

Reputation: 1553

Authenticating FastAPI session via requests

I am following the fastapi docs to implement an user authentication system. Here is a minimal example of app.py:

# import lines and utilities omitted
@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}


@app.get("/user/me", response_model=UserRead)
def read_user(*, session=Depends(get_session), current_user=Depends(get_current_user)):
    user = session.get(User, current_user.username)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user

When the user calls /users/me, it returns the current user. This works completely well as described in the tutorial in the SwaggerUI. But, I am not able to perform the same authorization and operation via python requests. Here is a following python code which I used:

import requests
backend_url = "http://localhost:8000/"
login_data =  {'username':'user1', 'password':'secret1'}
s = requests.Session()
s.post(backend_url + "token", login_data) # response 200
s.get(backend_url + "user/me") # response 401

I am looking for some ways by which I can reuse the access_token returned by fastapi.

Upvotes: 1

Views: 4443

Answers (2)

arunppsg
arunppsg

Reputation: 1553

I found the answer in docs of fastapi itself:

import requests

backend_url = "http://localhost:8000/"
login_data =  {'username':'user1', 'password':'secret1'}

session = requests.Session()
response = session.post(backend_url + "token", login_data)
response = json.loads(response.content.decode('utf-8'))

session.headers.update({"Authorization": 'Bearer ' + response['access_token']})

session.get(backend_url + "user/me")

Upvotes: 2

glory9211
glory9211

Reputation: 843

You are not using the session variable s = requests.Session() to send HTTP requests. So the post and get methods are getting sent independently from each other. Try using

s = requests.Session()
s.post(backend_url + "token", login_data)  # use the session post method

s.get(backend_url + "user/me")  # use the session get method

Upvotes: 0

Related Questions