FastApi 422 Unprocessable Entity,关于身份验证,如何解决?

FastApi 422 Unprocessable Entity, on authentication, how to fix?

无法理解,即使我删除了所有内部函数并只打印了一些东西仍然出现此错误,但是当我使用 fastapi 文档并尝试用它签名时,它起作用了。

@auth_router.post('/signin')
async def sign_in(username: str = Form(...), password: str = Form(...)) -> dict:
    user = await authenticate_user(username, password)

    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED, 
            detail='Invalid username or password',
        )

    user_obj = await User_Pydantic.from_tortoise_orm(user)
    user_token = await generate_token(user_obj)

    return {
        'access_token': user_token,
        'token_type': 'bearer',
    }

在我使用 OAuth2PasswordRequestForm 之前,遇到 422 错误时,请尝试其他方式。

我的模型是 tortoise orm,需要的时候我会把它转换成 pydantic 模型, 在文档中一切正常。

JS

handleEvent(signinform, 'submit', e => {
    e.preventDefault();
    if(!isEmpty(signinform)){

        signInUsername = getElement('input[name="username"]', signinform).value;
        signInPassword = getElement('input[name="password"]', signinform).value;
        recaptchaV3 = getElement('[name="g-recaptcha-response"]').value;

        if(recaptchaV3){
            signInData = new FormData();
            signInData.append('username', signInUsername);
            signInData.append('password', signInPassword);

            isLogened = request('POST', '/signin', signInData);
            if(isLogened){
                log(isLogened);
            }
            
        } else{
            alert('Reload Page');
        }

    }

})

authenticate_user 函数

async def authenticate_user(username: str, password: str):
    user = await User.get(username=username)

    if not user or not user.verify_password(password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED, 
            detail='Invalid username or password',
        )
    return user

我的请求函数

const request = (method, url, data = null) => {
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest()
        xhr.open(method, url, true)
        xhr.setRequestHeader('Content-Type', 'application/json')
        xhr.onerror = function () {
            console.log(xhr.response);
        };
        xhr.onload = () => {
        if (xhr.status === 200) {
            return resolve(JSON.parse(xhr.responseText || '{}'))
            } else {
                return reject(new Error(`Request failed with status ${xhr.status}`))
            }
        } 
        if (data) {
            xhr.send(JSON.stringify(data))
        } else {
            xhr.send()
        }


    })
}

虽然你没有发布错误,但目的是告诉你问题所在,我相当确定问题出在你执行请求的方式上。

xhr.setRequestHeader('Content-Type', 'application/json')

表示你发送的是json数据,openapi的认证形式不接受。此外,您将数据字符串化为 json,这同样不是可接受的格式。

因此,将内容类型更改为 www-form-urlencoded 并将 FormData 对象添加到您的请求正文中,将使其生效。

您可以在下面的 github 讨论中看到它

https://github.com/tiangolo/fastapi/issues/2740 https://github.com/tiangolo/fastapi/issues/1431