Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Token request failed Google Auth
Forum Updated to NodeBB v4.3 + New Features

Token request failed Google Auth

Scheduled Pinned Locked Moved Unsolved General and Desktop
14 Posts 4 Posters 958 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • SGaistS Offline
    SGaistS Offline
    SGaist
    Lifetime Qt Champion
    wrote on last edited by
    #3

    Hi,

    Which version of Qt are you using ?

    Interested in AI ? www.idiap.ch
    Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

    K 1 Reply Last reply
    0
    • C Offline
      C Offline
      ChrisW67
      wrote on last edited by
      #4

      The redirect URI (where the response is returned to) has to be registered in the APIs console, and the error is indicating that you haven't done that, or haven't done it correctly.

      K 2 Replies Last reply
      0
      • SGaistS SGaist

        Hi,

        Which version of Qt are you using ?

        K Offline
        K Offline
        Kiovtorov
        wrote on last edited by
        #5

        Hi @SGaist
        I am using the newest 6.7 Qt version

        1 Reply Last reply
        0
        • C ChrisW67

          The redirect URI (where the response is returned to) has to be registered in the APIs console, and the error is indicating that you haven't done that, or haven't done it correctly.

          K Offline
          K Offline
          Kiovtorov
          wrote on last edited by
          #6
          This post is deleted!
          1 Reply Last reply
          0
          • C ChrisW67

            The redirect URI (where the response is returned to) has to be registered in the APIs console, and the error is indicating that you haven't done that, or haven't done it correctly.

            K Offline
            K Offline
            Kiovtorov
            wrote on last edited by
            #7

            Hi @ChrisW67
            I didn't have a localhost server running. I started a npm one and now I don't get any output. Not even any error or "REQUEST FINISHED"

            1 Reply Last reply
            0
            • K Offline
              K Offline
              Kiovtorov
              wrote on last edited by
              #8

              Update: I tried some debugging and managed to see that the app can not fetch the access token correctly. Why could that be

              1 Reply Last reply
              0
              • SGaistS Offline
                SGaistS Offline
                SGaist
                Lifetime Qt Champion
                wrote on last edited by
                #9

                What debugging did you do ?
                What kind of error did you get ?

                Interested in AI ? www.idiap.ch
                Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                K 1 Reply Last reply
                0
                • SGaistS SGaist

                  What debugging did you do ?
                  What kind of error did you get ?

                  K Offline
                  K Offline
                  Kiovtorov
                  wrote on last edited by
                  #10

                  @SGaist

                  GoogleGateway::GoogleGateway(QObject *parent) : QObject(parent)
                  {
                      this->google = new QOAuth2AuthorizationCodeFlow(this);
                      this->google->setScope("email profile openid");
                  
                      connect(this->google, &QOAuth2AuthorizationCodeFlow::authorizeWithBrowser, &QDesktopServices::openUrl);
                  
                      QByteArray val;
                      QFile file;
                      file.setFileName(QDir::toNativeSeparators("/Users/boyankiovtorov/Desktop/Finbank/App/auth.json"));
                      if(file.open(QIODevice::ReadOnly | QIODevice::Text))
                      {
                          val = file.readAll();
                          file.close();
                      }
                  
                      QJsonDocument document = QJsonDocument::fromJson(val);
                      QJsonObject object = document.object();
                      const auto settingsObject = object["web"].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());
                      qDebug() << redirectUri;
                      const auto port = static_cast<quint16>(redirectUri.port());
                  
                      this->google->setAuthorizationUrl(authUri);
                      this->google->setClientIdentifier(clientId);
                      this->google->setAccessTokenUrl(tokenUri);
                      this->google->setClientIdentifierSharedKey(clientSecret);
                  
                      auto replyHandler = new QOAuthHttpServerReplyHandler(port, this);
                      this->google->setReplyHandler(replyHandler);
                      this->google->grant();
                  
                      // OAuth Error Handling
                      connect(this->google, &QOAuth2AuthorizationCodeFlow::error, [](const QString &error, const QString &errorDescription, const QUrl &uri) {
                          qDebug() << "OAuth Error:" << error;
                          qDebug() << "Error Description:" << errorDescription;
                          qDebug() << "URI:" << uri;
                      });
                  
                      // Extract authorization code manually (optional, just for logging)
                      QUrl redirectUrl("http://localhost:8080/?state=j8KbevEV&code=4%2F0AVG7fiQZEMvWtwfRTL_TGOaMg4wdNJkWrTOlreLjPqa3viachinzC2WZtmLJqYyksuqHDA&scope=email+profile+openid");
                      QUrlQuery query(redirectUrl);
                      QString authorizationCode = query.queryItemValue("code");
                  
                      if (!authorizationCode.isEmpty()) {
                          qDebug() << "Authorization Code:" << authorizationCode;
                      }
                  
                      // Handle the access token after grant
                      connect(this->google, &QOAuth2AuthorizationCodeFlow::granted, [this]() {
                          qDebug() << "Access token:" << this->google->token();
                  
                          // Set up a request with the token manually
                          QUrl url("https://www.googleapis.com/oauth2/v3/userinfo");
                          QNetworkRequest request(url);
                          request.setRawHeader("Authorization", "Bearer " + this->google->token().toUtf8());
                  
                          auto reply = this->google->networkAccessManager()->get(request);
                  
                          connect(reply, &QNetworkReply::finished, [reply]() {
                              if (reply->error() != QNetworkReply::NoError) {
                                  qDebug() << "Network error:" << reply->errorString();
                                  qDebug() << "HTTP status code:" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
                              } else {
                                  qDebug() << "REQUEST FINISHED. Response:" << reply->readAll();
                              }
                          });
                      });
                  
                      qDebug() << "Grant called";  // Check if grant() is reached
                  }
                  
                  

                  and got an output of

                  Authorization Code: "4%2F0AVG7fiQZEMvWtwfRTL_TGOaMg4wdNJkWrTOlreLjPqa3viachinzC2WZtmLJqYyksuqHDA"
                  Grant called
                  

                  but it can't retrieve the accesss token

                  JonBJ 1 Reply Last reply
                  0
                  • K Offline
                    K Offline
                    Kiovtorov
                    wrote on last edited by
                    #11

                    Here is more info from the cloud
                    Screenshot 2024-10-14 at 12.40.49.png ![Screenshot 2024-10-14 at 12.42.07.png](Request Entity Too Large) Screenshot 2024-10-14 at 12.42.23.png

                    1 Reply Last reply
                    0
                    • K Kiovtorov

                      @SGaist

                      GoogleGateway::GoogleGateway(QObject *parent) : QObject(parent)
                      {
                          this->google = new QOAuth2AuthorizationCodeFlow(this);
                          this->google->setScope("email profile openid");
                      
                          connect(this->google, &QOAuth2AuthorizationCodeFlow::authorizeWithBrowser, &QDesktopServices::openUrl);
                      
                          QByteArray val;
                          QFile file;
                          file.setFileName(QDir::toNativeSeparators("/Users/boyankiovtorov/Desktop/Finbank/App/auth.json"));
                          if(file.open(QIODevice::ReadOnly | QIODevice::Text))
                          {
                              val = file.readAll();
                              file.close();
                          }
                      
                          QJsonDocument document = QJsonDocument::fromJson(val);
                          QJsonObject object = document.object();
                          const auto settingsObject = object["web"].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());
                          qDebug() << redirectUri;
                          const auto port = static_cast<quint16>(redirectUri.port());
                      
                          this->google->setAuthorizationUrl(authUri);
                          this->google->setClientIdentifier(clientId);
                          this->google->setAccessTokenUrl(tokenUri);
                          this->google->setClientIdentifierSharedKey(clientSecret);
                      
                          auto replyHandler = new QOAuthHttpServerReplyHandler(port, this);
                          this->google->setReplyHandler(replyHandler);
                          this->google->grant();
                      
                          // OAuth Error Handling
                          connect(this->google, &QOAuth2AuthorizationCodeFlow::error, [](const QString &error, const QString &errorDescription, const QUrl &uri) {
                              qDebug() << "OAuth Error:" << error;
                              qDebug() << "Error Description:" << errorDescription;
                              qDebug() << "URI:" << uri;
                          });
                      
                          // Extract authorization code manually (optional, just for logging)
                          QUrl redirectUrl("http://localhost:8080/?state=j8KbevEV&code=4%2F0AVG7fiQZEMvWtwfRTL_TGOaMg4wdNJkWrTOlreLjPqa3viachinzC2WZtmLJqYyksuqHDA&scope=email+profile+openid");
                          QUrlQuery query(redirectUrl);
                          QString authorizationCode = query.queryItemValue("code");
                      
                          if (!authorizationCode.isEmpty()) {
                              qDebug() << "Authorization Code:" << authorizationCode;
                          }
                      
                          // Handle the access token after grant
                          connect(this->google, &QOAuth2AuthorizationCodeFlow::granted, [this]() {
                              qDebug() << "Access token:" << this->google->token();
                      
                              // Set up a request with the token manually
                              QUrl url("https://www.googleapis.com/oauth2/v3/userinfo");
                              QNetworkRequest request(url);
                              request.setRawHeader("Authorization", "Bearer " + this->google->token().toUtf8());
                      
                              auto reply = this->google->networkAccessManager()->get(request);
                      
                              connect(reply, &QNetworkReply::finished, [reply]() {
                                  if (reply->error() != QNetworkReply::NoError) {
                                      qDebug() << "Network error:" << reply->errorString();
                                      qDebug() << "HTTP status code:" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
                                  } else {
                                      qDebug() << "REQUEST FINISHED. Response:" << reply->readAll();
                                  }
                              });
                          });
                      
                          qDebug() << "Grant called";  // Check if grant() is reached
                      }
                      
                      

                      and got an output of

                      Authorization Code: "4%2F0AVG7fiQZEMvWtwfRTL_TGOaMg4wdNJkWrTOlreLjPqa3viachinzC2WZtmLJqYyksuqHDA"
                      Grant called
                      

                      but it can't retrieve the accesss token

                      JonBJ Offline
                      JonBJ Offline
                      JonB
                      wrote on last edited by
                      #12

                      @Kiovtorov
                      I know nothing about this :) So excuse me if this is quite wrong or irrelevant! Your grant/error would come from this->google->grant();, right? So wouldn't you want to connect() both the QOAuth2AuthorizationCodeFlow::error and QOAuth2AuthorizationCodeFlow::granted before calling grant() rather than afterwards? You probably know better than I and it won't make any difference, but it's just a thought? I connect my signals before I execute a statement which will result in signals rather than afterwards.

                      K 1 Reply Last reply
                      0
                      • JonBJ JonB

                        @Kiovtorov
                        I know nothing about this :) So excuse me if this is quite wrong or irrelevant! Your grant/error would come from this->google->grant();, right? So wouldn't you want to connect() both the QOAuth2AuthorizationCodeFlow::error and QOAuth2AuthorizationCodeFlow::granted before calling grant() rather than afterwards? You probably know better than I and it won't make any difference, but it's just a thought? I connect my signals before I execute a statement which will result in signals rather than afterwards.

                        K Offline
                        K Offline
                        Kiovtorov
                        wrote on last edited by Kiovtorov
                        #13

                        @JonB It does make sense
                        I changed it a bit

                        GoogleGateway::GoogleGateway(QObject *parent) : QObject(parent)
                        {
                            this->google = new QOAuth2AuthorizationCodeFlow(this);
                            this->google->setScope("openid email profile");
                            connect(this->google, &QOAuth2AuthorizationCodeFlow::authorizeWithBrowser, &QDesktopServices::openUrl);
                        
                            // Load OAuth settings from file
                            QByteArray val;
                            QFile file;
                            file.setFileName(QDir::toNativeSeparators("/Users/boyankiovtorov/Desktop/Finbank/App/auth.json"));
                            if(file.open(QIODevice::ReadOnly | QIODevice::Text))
                            {
                                val = file.readAll();
                                file.close();
                            }
                            else
                            {
                                qDebug() << "Failed to open auth.json file!";
                                return; // Exit if the file could not be opened
                            }
                        
                            QJsonDocument document = QJsonDocument::fromJson(val);
                            QJsonObject object = document.object();
                            const auto settingsObject = object["web"].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());
                            const auto port = static_cast<quint16>(redirectUri.port());
                        
                            // Log OAuth configuration details
                            qDebug() << "Auth URI:" << authUri;
                            qDebug() << "Client ID:" << clientId;
                            qDebug() << "Token URI:" << tokenUri;
                            qDebug() << "Client Secret:" << clientSecret;
                            qDebug() << "Redirect URI:" << redirectUri;
                        
                            this->google->setAuthorizationUrl(authUri);
                            this->google->setClientIdentifier(clientId);
                            this->google->setAccessTokenUrl(tokenUri);
                            this->google->setClientIdentifierSharedKey(clientSecret);
                        
                            auto replyHandler = new QOAuthHttpServerReplyHandler(port, this);
                            this->google->setReplyHandler(replyHandler);
                        
                            // Connect signals for granted and error before calling grant()
                            connect(this->google, &QOAuth2AuthorizationCodeFlow::granted, [this]() {
                                qDebug() << "Access Granted!";
                                qDebug() << "Access Token:" << this->google->token(); // Log access token
                        
                                // Make a request to the Google People API to fetch user info
                                QUrl userInfoUrl("https://www.googleapis.com/oauth2/v3/userinfo");
                                auto reply = this->google->get(userInfoUrl);
                        
                                connect(reply, &QNetworkReply::finished, [reply]() {
                                    if (reply->error() != QNetworkReply::NoError) {
                                        qDebug() << "Network error:" << reply->errorString();
                                        qDebug() << "Response code:" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
                                        qDebug() << "Response body:" << reply->readAll(); // Log raw response
                                    } else {
                                        // Parse the JSON response
                                        QByteArray responseData = reply->readAll();
                                        QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);
                                        QJsonObject jsonObj = jsonDoc.object();
                        
                                        // Print out some user info (e.g., email, name, etc.)
                                        qDebug() << "User Info:";
                                        qDebug() << "Email:" << jsonObj["email"].toString();
                                        qDebug() << "Name:" << jsonObj["name"].toString();
                                        qDebug() << "Picture URL:" << jsonObj["picture"].toString();
                                    }
                                    reply->deleteLater();
                                });
                            });
                        
                            connect(this->google, &QOAuth2AuthorizationCodeFlow::error, [](const QString &errorString) {
                                qDebug() << "Authorization Error:" << errorString;
                            });
                        
                            // Now call grant()
                            qDebug() << "Initiating OAuth grant...";
                            this->google->grant();
                        }
                        
                        
                        

                        Output
                        Auth URI: QUrl("https://accounts.google.com/o/oauth2/auth")
                        Client ID: "client id"
                        Token URI: QUrl("https://oauth2.googleapis.com/token")
                        Client Secret: "client secret"
                        Redirect URI: QUrl("http://127.0.0.1:8080/")
                        Initiating OAuth grant...

                        but I still can't get to "Acess granted!" and no user info is displayed
                        Some suggestions on debugging?

                        1 Reply Last reply
                        0
                        • K Offline
                          K Offline
                          Kiovtorov
                          wrote on last edited by
                          #14

                          I added Google People Api, changed the ports, ensured all the urls, tried different online methods but can't gather the user info. If someone has a working code might be helpful to manage why so.

                          1 Reply Last reply
                          0

                          • Login

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • Users
                          • Groups
                          • Search
                          • Get Qt Extensions
                          • Unsolved