Send Headers in a QOAuth2AuthorizationCodeFlow request
-
Hi all,
I am using networkauth for connecting to an OAuth application. I have been able to successfully authenticate after I receive the QOAuth2AuthorizationCodeFlow::granted signal.
Had it been a normal QNAM request, it would have been easy. But with networkauth, I don't have access to AccessToken. So I cannot directly send a QNAM request
Now, what is the correct way to send an additional header with my request? Here is my code
// private // QOAuth2AuthorizationCodeFlow * myObject connect(this->myObject, &QOAuth2AuthorizationCodeFlow::granted, [=](){ qDebug() << __FUNCTION__ << __LINE__ << "Access Granted!"; auto m_networkReply = this->myObject->post(QUrl("API_URL")); // Here I need to post a header in m_networkReply // setHeader(QNetworkRequest::ContentTypeHeader,"application/json") // How do I do it? connect(m_networkReply, &QNetworkReply::finished, [=](){ qDebug() << "REQUEST FINISHED. Error? " << (m_networkReply->error() != QNetworkReply::NoError); qDebug() << m_networkReply->readAll(); }); });
Thank you
-
@chilarai Hey, using the AuthorizationCodeFlow as you do you should have several possibilities looking at this,
https://doc.qt.io/qt-5/qoauth2authorizationcodeflow.html#accessTokenUrlThis was also posted here the other day, near the bottom the blog entry there is some examples to connect after receiving the granted signal.
https://www.qt.io/blog/2017/01/25/connecting-qt-application-google-services-using-oauth-2-0 -
I found the solution to my question. AccessToken can be obtained by this->myObject->token() and the Header can be set using
m_networkRequest.setRawHeader("Authorization", "Bearer " + this->myObject->token().toUtf8());
So my code snippet becomes
// private // QOAuth2AuthorizationCodeFlow * myObject connect(this->myObject, &QOAuth2AuthorizationCodeFlow::granted, [=](){ qDebug() << __FUNCTION__ << __LINE__ << "Access Granted!"; QJsonObject obj; obj.insert("param1", "someval"); QJsonDocument doc(obj); QString strJson(doc.toJson(QJsonDocument::Compact)); QNetworkRequest m_networkRequest; m_networkRequest.setUrl(QUrl("API_URL")); m_networkRequest.setHeader(QNetworkRequest::ContentTypeHeader,"application/json"); m_networkRequest.setRawHeader("Authorization", "Bearer " + this->myObject->token().toUtf8()); auto m_networkReply = m_networkAccessManager->post(m_networkRequest, strJson.toUtf8()); connect(m_networkReply, &QNetworkReply::finished, [=](){ qDebug() << "REQUEST FINISHED. Error? " << (m_networkReply->error() != QNetworkReply::NoError); qDebug() << m_networkReply->readAll(); }); });