I want to find out how to fix this error. I'm using python-jose(Poetry) in FastAPI. (I apologize if there have mistake in my sentences, because I don't use Google Translate, to improve my English skills). python-jose[cryptograph]
async def get_current_user(
db: AsyncSession = Depends(get_async_session), token: str = Security(oauth2_scheme)
):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
token_data = Token(**payload)
except PyJWTError:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="Could not validate credentials"
)
user = await crud_user.get(db, id=token_data.id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
It's working, namely creating JWT token:
@router.post("/token", response_model=Token, tags=['login'])
async def login_access_token(
db_session: AsyncSession = Depends(get_async_session),
form_data: OAuth2PasswordRequestForm = Depends()
):
user = await crud_user.authenticate(db_session=db_session,
email=form_data.username, password=form_data.password)
if not user:
raise HTTPException(
status_code=404, detail="Incorret password or username"
)
elif not await crud_user.is_active(user):
raise HTTPException(
status_code=400, detail="Inactive user"
)
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
return {
"access_type": await create_access_token(
data = {"user_id": user.id}, expires_delta=access_token_expires
),
"token_type": "bearer"
}
This is my version for creating JWT token:
async def create_access_token(*, data: dict, expires_delta: timedelta = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire, "sub": access_token_jwt_subject})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
I'm writhing async code, written across requirements.txt with using ordinary Jose and it worked out
But using Poetry Jose didn't allow use jose, because pycripto very old for these dependencies, and I was beginning to use python-jose and received this error:
payload = jwt.decode(token, key=key, algorithms=[ALGORITHM]) File "D:\test_fastapi\test_fastapi_2\test_fastapi_3\venv\lib\site-packages\jose\jwt.py", line 144, in decode raise JWTError(e) jose.exceptions.JWTError: Not enough segments
Looked about this problem and didn't find anything exactly about python-jose
Can you help me to fix this problem? If I need to add something, please let me know.
This code doesn't work:
@router.post("/current_user/login", tags=["login"],
response_model=User)
async def get_current_user_au(get_current_user: DBUser =
Depends(get_current_user)):
return get_current_user
I have watched in docs about Python-Jose and there they are using this option:
jwt.decode(token, 'secret', algorithms=['HS256'])
And I have a SECRET_KEY, token: str = Security(oauth2_scheme), and algorithms and can't understand what I'm doing wrong.