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. 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.

I have tried the instructions provided here like clearing browser cache and logging in/out of account. I have also made sure I am using the correct URL that google lists in their documentation. My first method is responsible for getting the access token. The second handles the uploads.

void
googleDriveInterface::getAuthentication() {
   google = new QOAuth2AuthorizationCodeFlow;
   google->setScope("");
   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("");
    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.

1 Answer

error 401 unauthorized

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. The access token must be a bearer token as far as i can see your not passing bearer.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest