Google Sign-In Qt6 Desktop Working Code
Solved
General and Desktop
-
I had trouble finding a working example for the google API in Qt6 of any kind so I thought I would drop the code here for you all to have. Once I figure out the mobile side of things, I'll be back with an update. Any pointers on how to pull that redirect_uri off on mobile would be helpful. I'm playing with native and php methods at the moment. But I'm not sure which method is going to produce.
Steve
QString clientId = "CLIENT ID FROM API CREDENTIALS"; QString authUri = "https://accounts.google.com/o/oauth2/auth"; QString tokenUri = "https://accounts.google.com/o/oauth2/token"; QStringList redirectUris; redirectUris << "http://127.0.0.1:54321/"; //ensure this is included in the API credentials under authorized URI QString redirectUri = redirectUris[0]; QString clientSecret = "YOUR CLIENT SECRET FROM API CREDENTIALS"; auto google = new QOAuth2AuthorizationCodeFlow(this); google->setScope("email"); google->setAuthorizationUrl(authUri); google->setClientIdentifier(clientId); google->setAccessTokenUrl(tokenUri); google->setClientIdentifierSharedKey(clientSecret); // Use the same port number as above auto replyHandler = new QOAuthHttpServerReplyHandler(54321, this); google->setReplyHandler(replyHandler); // Set up the function to modify AND REPLACE the parameters google->setModifyParametersFunction([](QAbstractOAuth::Stage stage, QMultiMap<QString, QVariant>* parameters) { if (stage == QAbstractOAuth::Stage::RequestingAccessToken) { auto encodedCode = parameters->value("code").toByteArray(); parameters->replace("code", QUrl::fromPercentEncoding(encodedCode)); } }); // Connect the signals to retrieve the tokens, if you want to see them connect(google, &QOAuth2AuthorizationCodeFlow::tokenChanged, [=](const QString &token) { qDebug() << "Token changed:" << token; }); connect(replyHandler, &QOAuthHttpServerReplyHandler::tokensReceived, [](const QVariantMap &tokens) { qDebug() << "Tokens received:" << tokens; }); connect(google, &QOAuth2AuthorizationCodeFlow::authorizeWithBrowser, &QDesktopServices::openUrl); // Once you are granted access, make a request via the Google API connect(google, &QOAuth2AuthorizationCodeFlow::granted, [=] { qDebug() << "in the granted block now"; // This block is run once you have logged into the browser successfully auto rep = google->get(QUrl("https://www.googleapis.com/oauth2/v1/userinfo?alt=json")); QEventLoop loop; connect(rep, &QNetworkReply::finished, &loop, &QEventLoop::quit); loop.exec(); QString currentByteArray = rep->readAll(); qDebug() << "network reply google api connect step get info" << currentByteArray; }); google->grant();
-
-
Where did you use the redirectUri? It does not appear in your code