Store OAuth 2 token from Google API for future requests












1















I can authorize and make authorized requests to Google API using the documentation and sample code (from Authorizing and Making Authorized Requests):



<html>
<head></head>
<body>
<script type="text/javascript">
function handleClientLoad() {
// Loads the client library and the auth2 library together for efficiency.
// Loading the auth2 library is optional here since `gapi.client.init` function will load
// it if not already loaded. Loading it upfront can save one network request.
gapi.load('client:auth2', initClient);
}

function initClient() {
// Initialize the client with API key and People API, and initialize OAuth with an
// OAuth 2.0 client ID and scopes (space delimited string) to request access.
gapi.client.init({
apiKey: 'YOUR_API_KEY',
discoveryDocs: ["https://people.googleapis.com/$discovery/rest?version=v1"],
clientId: 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com',
scope: 'profile'
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
});
}

function updateSigninStatus(isSignedIn) {
// When signin status changes, this function is called.
// If the signin status is changed to signedIn, we make an API call.
if (isSignedIn) {
makeApiCall();
}
}

function handleSignInClick(event) {
// Ideally the button should only show up after gapi.client.init finishes, so that this
// handler won't be called before OAuth is initialized.
gapi.auth2.getAuthInstance().signIn();
}

function handleSignOutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}

function makeApiCall() {
// Make an API call to the People API, and print the user's given name.
gapi.client.people.people.get({
'resourceName': 'people/me',
'requestMask.includeField': 'person.names'
}).then(function(response) {
console.log('Hello, ' + response.result.names[0].givenName);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
<button id="signin-button" onclick="handleSignInClick()">Sign In</button>
<button id="signout-button" onclick="handleSignOutClick()">Sign Out</button>
</body>
</html>


However, I can only make requests as long as the session is alive. What I want is to store the token in a database and then make requests using this token.



Ultimately, I want to have a user settings page where the user can give consent to the app (i.e. link/unlink Google API), so they always can see if they have authorized and when the access token has to be renewed. I want it to behave similar to when users usually can link/unlink "Sign in with Facebook/Google/GitHub" in their account settings.



But I don't in the Google API documentation how to retrieve the token and how to make requests based on the shortlived token.



How do I accomplish this? Are there any examples of doing this in the Google API documentation?










share|improve this question





























    1















    I can authorize and make authorized requests to Google API using the documentation and sample code (from Authorizing and Making Authorized Requests):



    <html>
    <head></head>
    <body>
    <script type="text/javascript">
    function handleClientLoad() {
    // Loads the client library and the auth2 library together for efficiency.
    // Loading the auth2 library is optional here since `gapi.client.init` function will load
    // it if not already loaded. Loading it upfront can save one network request.
    gapi.load('client:auth2', initClient);
    }

    function initClient() {
    // Initialize the client with API key and People API, and initialize OAuth with an
    // OAuth 2.0 client ID and scopes (space delimited string) to request access.
    gapi.client.init({
    apiKey: 'YOUR_API_KEY',
    discoveryDocs: ["https://people.googleapis.com/$discovery/rest?version=v1"],
    clientId: 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com',
    scope: 'profile'
    }).then(function () {
    // Listen for sign-in state changes.
    gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

    // Handle the initial sign-in state.
    updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
    });
    }

    function updateSigninStatus(isSignedIn) {
    // When signin status changes, this function is called.
    // If the signin status is changed to signedIn, we make an API call.
    if (isSignedIn) {
    makeApiCall();
    }
    }

    function handleSignInClick(event) {
    // Ideally the button should only show up after gapi.client.init finishes, so that this
    // handler won't be called before OAuth is initialized.
    gapi.auth2.getAuthInstance().signIn();
    }

    function handleSignOutClick(event) {
    gapi.auth2.getAuthInstance().signOut();
    }

    function makeApiCall() {
    // Make an API call to the People API, and print the user's given name.
    gapi.client.people.people.get({
    'resourceName': 'people/me',
    'requestMask.includeField': 'person.names'
    }).then(function(response) {
    console.log('Hello, ' + response.result.names[0].givenName);
    }, function(reason) {
    console.log('Error: ' + reason.result.error.message);
    });
    }
    </script>
    <script async defer src="https://apis.google.com/js/api.js"
    onload="this.onload=function(){};handleClientLoad()"
    onreadystatechange="if (this.readyState === 'complete') this.onload()">
    </script>
    <button id="signin-button" onclick="handleSignInClick()">Sign In</button>
    <button id="signout-button" onclick="handleSignOutClick()">Sign Out</button>
    </body>
    </html>


    However, I can only make requests as long as the session is alive. What I want is to store the token in a database and then make requests using this token.



    Ultimately, I want to have a user settings page where the user can give consent to the app (i.e. link/unlink Google API), so they always can see if they have authorized and when the access token has to be renewed. I want it to behave similar to when users usually can link/unlink "Sign in with Facebook/Google/GitHub" in their account settings.



    But I don't in the Google API documentation how to retrieve the token and how to make requests based on the shortlived token.



    How do I accomplish this? Are there any examples of doing this in the Google API documentation?










    share|improve this question



























      1












      1








      1


      1






      I can authorize and make authorized requests to Google API using the documentation and sample code (from Authorizing and Making Authorized Requests):



      <html>
      <head></head>
      <body>
      <script type="text/javascript">
      function handleClientLoad() {
      // Loads the client library and the auth2 library together for efficiency.
      // Loading the auth2 library is optional here since `gapi.client.init` function will load
      // it if not already loaded. Loading it upfront can save one network request.
      gapi.load('client:auth2', initClient);
      }

      function initClient() {
      // Initialize the client with API key and People API, and initialize OAuth with an
      // OAuth 2.0 client ID and scopes (space delimited string) to request access.
      gapi.client.init({
      apiKey: 'YOUR_API_KEY',
      discoveryDocs: ["https://people.googleapis.com/$discovery/rest?version=v1"],
      clientId: 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com',
      scope: 'profile'
      }).then(function () {
      // Listen for sign-in state changes.
      gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

      // Handle the initial sign-in state.
      updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
      });
      }

      function updateSigninStatus(isSignedIn) {
      // When signin status changes, this function is called.
      // If the signin status is changed to signedIn, we make an API call.
      if (isSignedIn) {
      makeApiCall();
      }
      }

      function handleSignInClick(event) {
      // Ideally the button should only show up after gapi.client.init finishes, so that this
      // handler won't be called before OAuth is initialized.
      gapi.auth2.getAuthInstance().signIn();
      }

      function handleSignOutClick(event) {
      gapi.auth2.getAuthInstance().signOut();
      }

      function makeApiCall() {
      // Make an API call to the People API, and print the user's given name.
      gapi.client.people.people.get({
      'resourceName': 'people/me',
      'requestMask.includeField': 'person.names'
      }).then(function(response) {
      console.log('Hello, ' + response.result.names[0].givenName);
      }, function(reason) {
      console.log('Error: ' + reason.result.error.message);
      });
      }
      </script>
      <script async defer src="https://apis.google.com/js/api.js"
      onload="this.onload=function(){};handleClientLoad()"
      onreadystatechange="if (this.readyState === 'complete') this.onload()">
      </script>
      <button id="signin-button" onclick="handleSignInClick()">Sign In</button>
      <button id="signout-button" onclick="handleSignOutClick()">Sign Out</button>
      </body>
      </html>


      However, I can only make requests as long as the session is alive. What I want is to store the token in a database and then make requests using this token.



      Ultimately, I want to have a user settings page where the user can give consent to the app (i.e. link/unlink Google API), so they always can see if they have authorized and when the access token has to be renewed. I want it to behave similar to when users usually can link/unlink "Sign in with Facebook/Google/GitHub" in their account settings.



      But I don't in the Google API documentation how to retrieve the token and how to make requests based on the shortlived token.



      How do I accomplish this? Are there any examples of doing this in the Google API documentation?










      share|improve this question
















      I can authorize and make authorized requests to Google API using the documentation and sample code (from Authorizing and Making Authorized Requests):



      <html>
      <head></head>
      <body>
      <script type="text/javascript">
      function handleClientLoad() {
      // Loads the client library and the auth2 library together for efficiency.
      // Loading the auth2 library is optional here since `gapi.client.init` function will load
      // it if not already loaded. Loading it upfront can save one network request.
      gapi.load('client:auth2', initClient);
      }

      function initClient() {
      // Initialize the client with API key and People API, and initialize OAuth with an
      // OAuth 2.0 client ID and scopes (space delimited string) to request access.
      gapi.client.init({
      apiKey: 'YOUR_API_KEY',
      discoveryDocs: ["https://people.googleapis.com/$discovery/rest?version=v1"],
      clientId: 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com',
      scope: 'profile'
      }).then(function () {
      // Listen for sign-in state changes.
      gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

      // Handle the initial sign-in state.
      updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
      });
      }

      function updateSigninStatus(isSignedIn) {
      // When signin status changes, this function is called.
      // If the signin status is changed to signedIn, we make an API call.
      if (isSignedIn) {
      makeApiCall();
      }
      }

      function handleSignInClick(event) {
      // Ideally the button should only show up after gapi.client.init finishes, so that this
      // handler won't be called before OAuth is initialized.
      gapi.auth2.getAuthInstance().signIn();
      }

      function handleSignOutClick(event) {
      gapi.auth2.getAuthInstance().signOut();
      }

      function makeApiCall() {
      // Make an API call to the People API, and print the user's given name.
      gapi.client.people.people.get({
      'resourceName': 'people/me',
      'requestMask.includeField': 'person.names'
      }).then(function(response) {
      console.log('Hello, ' + response.result.names[0].givenName);
      }, function(reason) {
      console.log('Error: ' + reason.result.error.message);
      });
      }
      </script>
      <script async defer src="https://apis.google.com/js/api.js"
      onload="this.onload=function(){};handleClientLoad()"
      onreadystatechange="if (this.readyState === 'complete') this.onload()">
      </script>
      <button id="signin-button" onclick="handleSignInClick()">Sign In</button>
      <button id="signout-button" onclick="handleSignOutClick()">Sign Out</button>
      </body>
      </html>


      However, I can only make requests as long as the session is alive. What I want is to store the token in a database and then make requests using this token.



      Ultimately, I want to have a user settings page where the user can give consent to the app (i.e. link/unlink Google API), so they always can see if they have authorized and when the access token has to be renewed. I want it to behave similar to when users usually can link/unlink "Sign in with Facebook/Google/GitHub" in their account settings.



      But I don't in the Google API documentation how to retrieve the token and how to make requests based on the shortlived token.



      How do I accomplish this? Are there any examples of doing this in the Google API documentation?







      javascript google-api google-calendar-api google-oauth google-oauth2






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 22 '18 at 12:11









      DaImTo

      45.7k1163245




      45.7k1163245










      asked Nov 22 '18 at 11:59









      JamgreenJamgreen

      2,603947111




      2,603947111
























          1 Answer
          1






          active

          oldest

          votes


















          0














          The token you are seeing is an access token. Access tokens are short lived tokens that give you access to a users data. What you need is a refresh token which will give you the ability to request a new access token when ever the access token you have expires (After an hour).



          You can not use refresh tokens with client sided applications. You will need to switch to a server sided solution like node.js, php, or python for example.



          You can read more about it here






          share|improve this answer
























          • Thanks for your answer. You mention a token I'm seeing, but I don't see any tokens at all. I just receive a popup to give consent to authorize with my Google account and then it seems the token is saved in gapi.client. I can at least provide requests to the platform by calling gapi.client, but I never provide any access token with my requests

            – Jamgreen
            Nov 22 '18 at 14:59











          • You wont see it its built into the Google api javascript client library. It handles all of this for you. This library and language does not have the ability to do what you are asking. You need to switch to something server sided.

            – DaImTo
            Nov 23 '18 at 9:24











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53430545%2fstore-oauth-2-token-from-google-api-for-future-requests%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          The token you are seeing is an access token. Access tokens are short lived tokens that give you access to a users data. What you need is a refresh token which will give you the ability to request a new access token when ever the access token you have expires (After an hour).



          You can not use refresh tokens with client sided applications. You will need to switch to a server sided solution like node.js, php, or python for example.



          You can read more about it here






          share|improve this answer
























          • Thanks for your answer. You mention a token I'm seeing, but I don't see any tokens at all. I just receive a popup to give consent to authorize with my Google account and then it seems the token is saved in gapi.client. I can at least provide requests to the platform by calling gapi.client, but I never provide any access token with my requests

            – Jamgreen
            Nov 22 '18 at 14:59











          • You wont see it its built into the Google api javascript client library. It handles all of this for you. This library and language does not have the ability to do what you are asking. You need to switch to something server sided.

            – DaImTo
            Nov 23 '18 at 9:24
















          0














          The token you are seeing is an access token. Access tokens are short lived tokens that give you access to a users data. What you need is a refresh token which will give you the ability to request a new access token when ever the access token you have expires (After an hour).



          You can not use refresh tokens with client sided applications. You will need to switch to a server sided solution like node.js, php, or python for example.



          You can read more about it here






          share|improve this answer
























          • Thanks for your answer. You mention a token I'm seeing, but I don't see any tokens at all. I just receive a popup to give consent to authorize with my Google account and then it seems the token is saved in gapi.client. I can at least provide requests to the platform by calling gapi.client, but I never provide any access token with my requests

            – Jamgreen
            Nov 22 '18 at 14:59











          • You wont see it its built into the Google api javascript client library. It handles all of this for you. This library and language does not have the ability to do what you are asking. You need to switch to something server sided.

            – DaImTo
            Nov 23 '18 at 9:24














          0












          0








          0







          The token you are seeing is an access token. Access tokens are short lived tokens that give you access to a users data. What you need is a refresh token which will give you the ability to request a new access token when ever the access token you have expires (After an hour).



          You can not use refresh tokens with client sided applications. You will need to switch to a server sided solution like node.js, php, or python for example.



          You can read more about it here






          share|improve this answer













          The token you are seeing is an access token. Access tokens are short lived tokens that give you access to a users data. What you need is a refresh token which will give you the ability to request a new access token when ever the access token you have expires (After an hour).



          You can not use refresh tokens with client sided applications. You will need to switch to a server sided solution like node.js, php, or python for example.



          You can read more about it here







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 22 '18 at 12:13









          DaImToDaImTo

          45.7k1163245




          45.7k1163245













          • Thanks for your answer. You mention a token I'm seeing, but I don't see any tokens at all. I just receive a popup to give consent to authorize with my Google account and then it seems the token is saved in gapi.client. I can at least provide requests to the platform by calling gapi.client, but I never provide any access token with my requests

            – Jamgreen
            Nov 22 '18 at 14:59











          • You wont see it its built into the Google api javascript client library. It handles all of this for you. This library and language does not have the ability to do what you are asking. You need to switch to something server sided.

            – DaImTo
            Nov 23 '18 at 9:24



















          • Thanks for your answer. You mention a token I'm seeing, but I don't see any tokens at all. I just receive a popup to give consent to authorize with my Google account and then it seems the token is saved in gapi.client. I can at least provide requests to the platform by calling gapi.client, but I never provide any access token with my requests

            – Jamgreen
            Nov 22 '18 at 14:59











          • You wont see it its built into the Google api javascript client library. It handles all of this for you. This library and language does not have the ability to do what you are asking. You need to switch to something server sided.

            – DaImTo
            Nov 23 '18 at 9:24

















          Thanks for your answer. You mention a token I'm seeing, but I don't see any tokens at all. I just receive a popup to give consent to authorize with my Google account and then it seems the token is saved in gapi.client. I can at least provide requests to the platform by calling gapi.client, but I never provide any access token with my requests

          – Jamgreen
          Nov 22 '18 at 14:59





          Thanks for your answer. You mention a token I'm seeing, but I don't see any tokens at all. I just receive a popup to give consent to authorize with my Google account and then it seems the token is saved in gapi.client. I can at least provide requests to the platform by calling gapi.client, but I never provide any access token with my requests

          – Jamgreen
          Nov 22 '18 at 14:59













          You wont see it its built into the Google api javascript client library. It handles all of this for you. This library and language does not have the ability to do what you are asking. You need to switch to something server sided.

          – DaImTo
          Nov 23 '18 at 9:24





          You wont see it its built into the Google api javascript client library. It handles all of this for you. This library and language does not have the ability to do what you are asking. You need to switch to something server sided.

          – DaImTo
          Nov 23 '18 at 9:24




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53430545%2fstore-oauth-2-token-from-google-api-for-future-requests%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          MongoDB - Not Authorized To Execute Command

          Npm cannot find a required file even through it is in the searched directory

          in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith