Search code examples
google-apps-scriptgoogle-oauthgoogle-apps-script-api

How to refresh an OAuth token before calling the Execution API?


I am calling the app script execution API from my web app. I am getting ScriptApp.getOauthToken() and storing it inside sheet. When I open my web app I will get the stored access token and calling the execution API with the help of it.

But the problem is, after some time the token is getting expired and it is saying

authorization is required

when I call execution API.

Is there any way to keep access token alive or refreshing it whenever is needed?


Solution

  • I. You cannot and you should not. At least not natively

    There is no native Google Apps Script service method for obtaining and exchanging a refresh token (and you would need one if you want to refresh an expired OAuth 2.0 token) for a bearer token. That said, there is no practical reason in storing the short-lived token obtained via getOauthToken method - if a user authorized your application, you can request a token on the fly each time you need to make a request.

    II. If you still want to, use a library

    There is an officially endorsed library for Google Apps Script that manages OAuth 2.0 flow for you. When using it, you can obtain a refresh token if you set the offline access to true when issuing the token.

    III. If you really want to DIY, you can always make your own flow

    It is possible to perform a complete Oauth 2.0 flow (both with and without user interaction) by using only the native tools by building a custom JWT token and exchanging it with Google Identity Platform endpoints. But that means you will have to manage everything:

    1. Build JWT custom token headers and payload, then base64 urlencode them and sign with an appropriate signature and concatenate into a token.
    2. Exchange the custom JWT for a short-lived bearer token, validate it and extract expiration time, then persist the token.
    3. Each time you get the token from storage, check for the expiration time, and reissue the token again using the procedure in point 1 - 2.
    4. Handle token revocation (note that you will not be able to invalidate it from Google's servers, only in your application).
    5. And many more caveats along the way.

    Note that the token cannot be "kept alive", it goes against the idea behind the OAuth protocol - the lesser the lifespan of an individual token, the better the security of your application.