FastApi can't login using jwt authentication

Viewed 30

I am getting 422 Unprocessable Entity when trying to login. see the screenshot:

enter image description here

my jwt access token generating which I checked from my login route: see the screenshot:

enter image description here

here is my code for jwt access token:

SECRET_KEY = ""
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/login")

def create_access_token(data: dict):
    to_encode = data.copy()
    expire = datetime.utcnow() + timedelta(ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt


def verify_token(token:str,  credentials_exception):
    try:
            payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
            mobile_number: str = payload.get("sub")
            if mobile_number is None:
                raise credentials_exception
            token_data = schemas.TokenData(mobile_number=mobile_number)
             
    except JWTError:
            raise credentials_exception

async def get_current_user(token: str = Depends(oauth2_scheme)):
        credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"}, 
    )
        
        return token.verify_token(token,credentials_exception)

here is my login route:

    @router.post("/login")
    def user_login(form_data: OAuth2PasswordRequestForm = Depends(),db: Session = Depends(get_db), mobile_number: str = Form(),password: str = Form(), ):
    .... my othres code

where I am doing mistake?

0 Answers
Related