Home > Enterprise >  Angular/FastApi 422 issues
Angular/FastApi 422 issues

Time:04-02

I am having issues receiving 422 response errors from my fastapi server. I understand the response it is recieving does not match the pydantic model it is expecting, but I don't know why.
my request model:

@authenticate.post("/token", response_model=Token)
async def login_for_access_token(
        form_data: OAuth2PasswordRequestForm = Depends()):
    print(form_data)
    user = authenticate_user(
        form_data.username,
        form_data.password
    )
    print(f'User @ 104 = {user}')
    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=login_utility.get_expiration_time())
    access_token = create_access_token(
        data={"sub": user['username']}, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}

I am sending the request from an angular app using:

My payload:

{"username": blah, "password":password}
postTypeRequest(url: string, payload: any) {
    console.log(payload)
    console.log(this.REST_API_SERVER url)
    return this.httpClient.post(
      this.REST_API_SERVER url, payload).pipe(map(res => {
      return res;
    }));
  }

I am not having any issues sending the request via postman. I am a greenhorn using javascript/angular I am unsure of what I am doing wrong.

CodePudding user response:

As per the documentation:

OAuth2 specifies that when using the "password flow" (that we are using) the client/user must send a username and password fields as form data.

... the username and password must be sent as form data (so, no JSON here).

....OAuth2PasswordRequestForm is a class dependency that declares a form body with:

  • The username.
  • The password.
  • ...

Hence, you should be sending the credentials as form data. Have a look here, here and here on how to do this.

CodePudding user response:

Shouldn't the payload be: {username: "blah", password: "password"}

  • Related