1

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

Here is 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 and I am unsure of what I am doing wrong.

Chris
  • 18,724
  • 6
  • 46
  • 80
Drew
  • 33
  • 6

2 Answers2

0

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 at these AngularJS-related topics: here, here and here, as well as these FastAPI-related topics: here and here.

Chris
  • 18,724
  • 6
  • 46
  • 80
-1

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

Eddie Paz
  • 2,219
  • 16
  • 11
  • payload = {"username": blah, "password":password}. Am I missing something obvious here? – Drew Apr 02 '22 at 00:47
  • That's invalid JSON. Error: Parse error on line 1: {"username": blah, "password":pas -------------^ Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined' – Eddie Paz Apr 02 '22 at 02:33
  • ```{ "username": "tinkerbell", "password": "passsword" }```. Is this incorrect? This is the format being returned by formbuilder.group. Are extra steps required? – Drew Apr 02 '22 at 03:59