Search code examples
curloauthgoogle-apigoogle-drive-apigoogle-oauth

Uploading files to Google Drive using cURL - access_token expiry issue


My goal is to have a script with cURL requests that can be ran at anytime to upload a specified file to our Google Drive account without any manual input.

I'm able to upload a file to Google Drive using cURL when I use a freshly created "access_token".

However when I run the same cURL command to upload another file at a later time, I get an invalid credentials error.

And from reading, it's due to the "access_token" becoming expired. And in order to generate a new "access_token", I need to generate a new "user_code" and verify this code at "https://www.google.com/device".

Since I require a script to be ran without any manual input, I don't want to have to generate a "user_code" every time I need to upload a file since this is a manual step.

Should I be using the generated 'refresh_token' in the cURL request in order to upload a file at any given time?

Any help would be greatly appreciated.


Solution

  • In order to access a google api you need to have an access token. As you know access tokens expire after one hour, then you need to request a new access token. When you are authorizing the user the first time the wises course of action would be to request off line access as well. This will return to you a refeshtoken. Then when ever your code runs i recommend using the refresh token to request a new access token then you will always be running with an access token thats good for an hour.

    The following is ripped from one of my gists Googleauthnecation.sh

    Request access.

    Remember to add "offline" access to your scopes.

    # Client id from Google Developer console
    # Client Secret from Google Developer console
    # Scope this is a space separated list of the scopes of access you are requesting.
    
    # Authorization link.  Place this in a browser and copy the code that is returned after you accept the scopes.
    https://accounts.google.com/o/oauth2/auth?client_id=[Application Client Id]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=[Scopes]&response_type=code
    
    # Exchange Authorization code for an access token and a refresh token.
    
    curl \
    --request POST \
    --data "code=[Authentcation code from authorization link]&client_id=[Application Client Id]&client_secret=[Application Client Secret]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code" \
    https://accounts.google.com/o/oauth2/token
    

    exchange refresh token for a new access token.

    # Exchange a refresh token for a new access token.
    curl \
    --request POST \
    --data 'client_id=[Application Client Id]&client_secret=[Application Client Secret]&refresh_token=[Refresh token granted by second step]&grant_type=refresh_token' \
    https://accounts.google.com/o/oauth2/token
    

    Update:

    Also see How to connect to the Google Drive API using cURL?