简体   繁体   English

如何修复 401:发出 POST 请求时出现未经授权的错误 C++/Qt

[英]How to fix 401: Unauthorized Error when making a POST request C++/Qt

I am able to get the access token and refresh token but when I try to make a POST request to upload a file to Google Drive I get a 401 error.我能够获取访问令牌和刷新令牌,但是当我尝试发出 POST 请求以将文件上传到 Google Drive 时,我收到 401 错误。 I believe I haven't set the body of my request correctly to upload the file (still not 100% sure how to do that), but if that were the issue I would expect a 400 error.我相信我没有正确设置我的请求正文来上传文件(仍然不是 100% 确定如何做到这一点),但如果这是问题,我预计会出现 400 错误。

I have tried the instructions provided here https://airbrake.io/blog/http-errors/401-unauthorized-error like clearing browser cache and logging in/out of account.我已经尝试了此处提供的说明https://airbrake.io/blog/http-errors/401-unauthorized-error,例如清除浏览器缓存和登录/注销帐户。 I have also made sure I am using the correct URL that google lists in their documentation.我还确保我使用了谷歌在其文档中列出的正确 URL。 My first method is responsible for getting the access token.我的第一种方法负责获取访问令牌。 The second handles the uploads.第二个处理上传。

void
googleDriveInterface::getAuthentication() {
   google = new QOAuth2AuthorizationCodeFlow;
   google->setScope("https://www.googleapis.com/auth/drive");
   QObject::connect(google, &QOAuth2AuthorizationCodeFlow::authorizeWithBrowser, &QDesktopServices::openUrl); //this connection opens authorization URL in user's default browser

QJsonDocument credentials = getCredentials("googleDriveCredentials.json"); //json file data is loaded into credentials

//parse JSON
const auto object = credentials.object();
const auto settingsObject = object["installed"].toObject();
const QUrl authUri(settingsObject["auth_uri"].toString());
const auto clientID = settingsObject["client_id"].toString();
const QUrl tokenUri(settingsObject["token_uri"].toString());
const auto clientSecret(settingsObject["client_secret"].toString());
const auto redirectUris = settingsObject["redirect_uris"].toArray();
const QUrl redirectUri(redirectUris[0].toString()); //get first URI
const auto port = static_cast<quint16>(redirectUri.port()); // port needed to for QOAuthHttpServerReplyHandler

google->setAuthorizationUrl(authUri);
google->setClientIdentifier(clientID);
google->setAccessTokenUrl(tokenUri);
google->setClientIdentifierSharedKey(clientSecret);

auto replyHandler = new QOAuthHttpServerReplyHandler(port, this);
google->setReplyHandler(replyHandler);

QObject::connect(google, SIGNAL(granted()), this, SLOT(slotSetAuthToken())); //save token when access is granted
QObject::connect(google, SIGNAL(granted()), this, SLOT(testSlot()));
google->grant(); //start authorization process
}

void
googleDriveInterface::uploadFile(const QString &filePath) {
    QUrl uploadURL("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable");
    QNetworkRequest request(uploadURL);

QFile file(filePath);
if (!file.open(QIODevice::ReadOnly)) {
    qDebug() << "unable to open: " << filePath << " for upload:" << file.errorString();
    return;
}

//get size of file and save as qbytearray for request header
QByteArray fileSize;
fileSize.setNum(file.size());

//get MIME type of file
QMimeDatabase mimeDB; //contains a database of all MIME types
QMimeType mime = mimeDB.mimeTypeForFile(filePath);
QByteArray mimeType = mime.name().toUtf8();

QByteArray test = authToken.toUtf8();
//set headers
request.setRawHeader("Authorization", authToken.toUtf8()); //convert authToken to QByteArray when we set header;
request.setRawHeader("Content-Type", "application/json; charset=UTF-8");
request.setRawHeader("Content-Length", fileSize);
request.setRawHeader("X-Upload-Content-Type", mimeType);

QByteArray fileData = file.readAll();
file.close();

networkReply = networkManager->post(request, fileData);
QObject::connect(networkReply, SIGNAL(metaDataChanged()), this, SLOT(testSlot1()));
}

I am expecting to get 200 Status Ok but as previously mentioned I am getting error 401 unauthorized.我希望获得 200 Status Ok,但如前所述,我收到了未经授权的 401 错误。

error 401 unauthorized错误 401 未授权

Basically means that the request you are making has not been authorized.基本上意味着您提出的请求未经授权。

I am not a C++ dev this is just a guess from my oauth2 knowlage.我不是 C++ 开发人员,这只是我对 oauth2 知识的猜测。 The access token must be a bearer token as far as i can see your not passing bearer.访问令牌必须是不记名令牌,因为我可以看到您未通过的不记名令牌。

request.setRawHeader("Authorization", "bearer " authToken.toUtf8());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Qt / C ++中使用QWebkit进行POST请求 - POST request using QWebkit in Qt / C++ 使用 curlpp 在 C++ 中发出 POST 请求 - Making a POST request in C++ with curlpp 发送GetItem请求时出现HTTP 401未经授权的错误 - HTTP 401 Unauthorized error in sending GetItem Request 如何发出将发布查询和文件都上传到C ++ Qt中的服务器的http发布请求 - How to make an http post request that uploads both post queries & a file to a server in C++ Qt 在 C/C++ 中制作 libcurl json 发布请求 - Making libcurl json post request in C/C++ Qt或libcurl C ++:Facebook api POST请求以上传图片 - Qt or libcurl c++: Facebook api POST request to image upload 当moused结束时,alpha级别为0%的QPushButton变为稳定。 如何使用C ++修复Qt(使用样式表?) - QPushButton with an alpha level of 0% turns solid when moused over. How to fix Qt with C++ (with stylesheets?) C++ Curl post 请求不起作用且没有错误 - C++ Curl post request not working and no error 在C ++中调整数组大小时如何解决错误? - How to fix an error when resizing array in c++? 在 ESP32 上使用 C++ 发出 HTTP 请求时试图了解解析错误 - Trying to understand a parsing error when making an HTTP request with C++ on ESP32
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM