QAbstractOAuth2::refreshToken() returns an empty string when the QOAuth2AuthorizationCodeFlow::granted signal is emitted.
Solved
General and Desktop
-
wrote on 15 Mar 2024, 11:53 last edited by
In the code below, the authentication process is performed by QOAuth2AuthorizationCodeFlow.
This code works correctly to get the access token, but it does not return the refresh token.#include "qoauth2test.h" QOAuth2Test::QOAuth2Test(QObject *parent) : QObject(parent) { // Launch browser for authorization request connect(&google, &QOAuth2AuthorizationCodeFlow::authorizeWithBrowser, &QDesktopServices::openUrl); // Receive answer from authorization request process connect(&google, &QOAuth2AuthorizationCodeFlow::granted, this, &QOAuth2Test::onGranted); QString authUri = "https://accounts.google.com/o/oauth2/v2/auth"; QString clientId = "XXXX"; QString tokenUri = "https://accounts.google.com/o/oauth2/token"; QString clientSecret = "XXXX"; QString scope = "https://www.googleapis.com/auth/drive"; quint16 port = 8080; google.setAuthorizationUrl(authUri); google.setClientIdentifier(clientId); google.setAccessTokenUrl(tokenUri); google.setClientIdentifierSharedKey(clientSecret); google.setScope(scope); google.setModifyParametersFunction([&](QAbstractOAuth::Stage stage, QVariantMap* parameters) { // Percent-decode the "code" parameter so Google can match it if (stage == QAbstractOAuth::Stage::RequestingAccessToken) { QByteArray code = parameters->value("code").toByteArray(); (*parameters)["code"] = QUrl::fromPercentEncoding(code); } }); auto replyHandler = new QOAuthHttpServerReplyHandler(port, this); google.setReplyHandler(replyHandler); } void QOAuth2Test::grant() { google.grant(); } void QOAuth2Test::onGranted() { accessToken = google.token(); qInfo() << "access Token:"<< accessToken; refreshToken = google.refreshToken(); qInfo() << "refresh Token:"<< refreshToken; }
Please tell me if anyone knows the solution.
Thank you. -
wrote on 15 Mar 2024, 12:53 last edited by
I found the answer
You need to replaceconnect(&google, &QOAuth2AuthorizationCodeFlow::authorizeWithBrowser, &QDesktopServices::openUrl);
with
connect(this->google, &QOAuth2AuthorizationCodeFlow::authorizeWithBrowser, [=](QUrl url) { QUrlQuery query(url); query.addQueryItem("prompt", "consent"); // Param required to get data everytime query.addQueryItem("access_type", "offline"); // Needed for Refresh Token (as AccessToken expires shortly) url.setQuery(query); QDesktopServices::openUrl(url); });
-
Hi and welcome to devnet,
Glad you found a solution and thanks for sharing !
Would you mind explaining how you got the solution ?
-
Hi and welcome to devnet,
Glad you found a solution and thanks for sharing !
Would you mind explaining how you got the solution ?
wrote on 15 Mar 2024, 21:01 last edited by -
1/4