Search code examples
node.jsgoogle-sheetsgoogle-apigoogle-oauthgoogle-sheets-api

Error with authentication while using Google's Node.js Sheets API: The provided keyfile does not define a valid redirect URI


I am trying to write to a google sheet using the Node.js Google Sheets API, but when I run the script, using the command quoted bellow, I get the following error:

node append.js Spreadsheet-ID 0

Error: The provided keyfile does not define a valid
redirect URI. There must be at least one redirect URI defined, and this sample
assumes it redirects to 'http://localhost:3000/oauth2callback'.  Please edit
your keyfile, and add a 'redirect_uris' section.  For example:

"redirect_uris": [
  "http://localhost:3000/oauth2callback"
]

    at authenticate (/folder/node_modules/@google-cloud/local-auth/build/src/index.js:56:15)
    at runSample (/folder/append.js:24:22)
    at Object.<anonymous> (/folder/append.js:52:3)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)

I am using the append.js script provided by Google in their googleapis Github repository.

My oauth2.keys.json file:

{
    "web": {
        "client_id": "my-client-id.apps.googleusercontent.com",
        "project_id": "my-id",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://oauth2.googleapis.com/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "client_secret": "client_secret",
        "redirect_uris": [
            "https://my-site.net"
        ]
    }
}


Solution

  • You need a valid redirect URI

    I know, that's what the error says, I am sorry to just repeat that, however, it is the clue to what you are getting tripped up on.

    After the application is successfully authorized the redirect URI can't just be "https://my-site.net". The resource at the URI needs to be able to handle the OAuth2 response which will either contain an authorization code or an error response.

    Here is a link to the Google guide for handling the server response.

    Here is an issue from the Github Repo, linked because it is a good case study of someone who had a similar problem to yours and could help you out as you work out how to authenticate your application.

    The Oauth2 docs that Google provide have extensive information and guides to help.