[英]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.