i am new to FastAPI, trying to get the token from the requests based on oauth2_scheme, but the token is undefined,i am providing a snippet below:
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/token")
def get_current_user(token: str = Depends(oauth2_scheme)):
"""
Get the current user from the JWT token.
"""
print("+++++++++++++++++++++++++++++++++++++")
print(token)
token_data = decode_access_token(token)
return {"username": token_data.username, "id": token_data.user_id}
i printed the token just to preview it but it print an undefined, what am i doing wrong why is the oauth2_scheme unable to correctly extract the token
I found a solution to the problem, I realized that FastAPI's SwaggerUI looks out for a particular keyword from the create_token endpoint which is 'access_token' instead of just 'token'. code snippet below:
@router.post("/token")
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(form_data.username, form_data.password)
if not user:
raise token_exception()
token = create_access_token({"sub": user["username"], "id": user["id"]})
return {"access_token": token}