Search code examples
node.jsoauth-2.0google-sheetsgoogle-sheets-apigoogle-oauth

Access google spreadsheet with JSON format key


I'm trying to access google table with node.js. There's a pretty good looking API, but it's using .pem file to authenticate aplication. The second way is to use client_id, client_secret and refresh_token for oauth2 or something named accesstoken. But what I've got from google dev console is a JSON formated key:

{
        type: 'service_account',
        project_id: 'fu...ng-1234',
        private_key_id: '2fd...0ba',
        private_key: '-----BEGIN PRIVATE KEY ... END PRIVATE KEY-----\n',
        client_email: '[email protected]',
        client_id: '10...51',
        auth_uri: 'https://accounts.google.com/o/oauth2/auth',
        token_uri: 'https://accounts.google.com/o/oauth2/token',
        auth_provider_x509_cert_url: 'https://www.googleapis.com/oauth2/v1/certs',
        client_x509_cert_url: 'https://www.googleapis.com/robot/v1/metadata/x509/...%40appspot.gserviceaccount.com'
}

I know how to export private_key to .pem file, but that doesn't look like a pure solution to me, because it means an extra file and potencional security risk. And also it's used by oauth and there's a possibility to use oauth2. So, is there a way how to use these JSON formated info to access google spreadsheet with this API using oauth2 ?

Thank you so much for any answer.


Solution

  • Yes, you can access Google spreadsheet with Google Sheet API using Oauth 2.0. When you requests to the Google API for non public user, data must be authorized by an authenticated user.

    The details of the authorization process for Oauth2.0 vary somewhat depending on what kind of application you're writing.

    The following process applies to all application:

    • When you create your application, you register it with Google. Google then provides information you'll need later, such as a client ID and a client secret.
    • When your application needs access to user data, it asks Google for a particular scope of access.
    • Google displays an OAuth dialog to the user, asking them to authorize your application to request some of their data.
    • If the user approves, then Google gives your application a short-lived access token.
    • Your application requests user data, attaching the access token to the request.
    • If Google determines that your request and the token are valid, it returns the requested data.

    Your application needs the scope information, as well as information that Google supplies during application registration (such as the client ID and/or the client secret).

    Version v4 of the Google Sheets API is now available, please migrate your app now. This migration guide shows how to update applications to use v4: https://developers.google.com/sheets/guides/concepts