Skip to content Skip to sidebar Skip to footer

How Can I Retrieve A Service Account Oauth2 Token From Google Api With Javascript?

I need to use a google projects service account to access google API using JavaScript. In order to do this I need to OAuth2 to google API servers to get an auth token. I understand

Solution 1:

There are two major divisions to this task.

  1. Configuring
  2. Coding

First the Configuration steps.

  • If you don't have a google account:
    1. Navigate to google.com
    2. Find and Click "Sign In"
    3. Click "More Options"
    4. Click "Create Account"
    5. Follow the steps to create an account
  • Navigate to the api dashboard: console.developers.google.com/apis/dashboard
  • Select or create a project by clicking on the current project. The project I have showing is called "My Project" enter image description here

  • Click google enable apis and services and enable those API you plan to work with

  • navigate to the credentials section: console.developers.google.com/apis/credentials
  • Click google create credentials and select "Service account key"
  • Ensure "Key Type" is "Json" and click "Create". You're key/cert will automatically download

Now for the Coding portion.

  • First download jsrsasign and add reference to "jsrsasign-all-min.js". If you want you can download just "jsrsasign-all-min.js" from github
  • Second update the following script with your cert/key (downloaded earlier):

    functionpostJWT(jwt, callback) {
        var xhttp = newXMLHttpRequest();
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4) {
                if (this.status == 200 && callback) {
                    callback(this.responseText);
                    return;
                }
                if (console) console.log(this.responseText);
            }
        };
        var parameters = "grant_type=" + encodeURIComponent("urn:ietf:params:oauth:grant-type:jwt-bearer") + "&assertion=" + encodeURIComponent(jwt);
        xhttp.open("POST", "https://www.googleapis.com/oauth2/v4/token", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send(parameters);
    }
    
    functiongetCert() {
        var cert = //your json key (downloaded earlier) goes here
            {
                "type": "service_account",
                "project_id": "proj..",
                "private_key_id": "e18..",
                "private_key": "-----BEGIN PRIVATE KEY-----\nMII..==\n-----END PRIVATE KEY-----\n",
                "client_email": "service-account@...iam.gserviceaccount.com",
                "client_id": "5761..",
                "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/..service-account%40...iam.gserviceaccount.com"
            };      
        return cert;
    }
    functiongetJWT() {
        var cert = getCert();
        var key = KEYUTIL.getKey(cert.private_key);
        var headers = { "alg": "RS256", "typ": "JWT" };
        var issued = Math.floor(newDate().getTime()/1000);
    
        var claims = {
            "iss": cert.client_email,
            "scope": "https://www.googleapis.com/auth/analytics.readonly",
            "aud": "https://www.googleapis.com/oauth2/v4/token",
            "exp": issued + 3600,
            "iat": issued
        };
    
        var jwt = KJUR.jws.JWS.sign(headers.alg, headers, JSON.stringify(claims), key);
        return jwt;
    }
    
  • When you test your code you should receive a json object back with an auth token. You can test your implementation like so:

    postJWT(getJWT(text), function(){
        let token = JSON.parse(response).access_token;
        //Do your api calls here using the token. //Reuse the token for up to 1 hour.
    });
    

Here is an example successful json object with token:

{"access_token":"ya29.c.ElkABZznrLNLK6ZAq2ybiH5lsRJpABE8p7MlZZJ0WCKcDNDv75lh-o1iRX__uMNUKSySiawm4YJGsbfqJH2JH61nRK6O2m0GJR7DgkEmo6ZlKtrvzke9C3xpwA","token_type":"Bearer","expires_in":3600}

Please note that this approach requires that the key/cert be accessible from your javascript environment. If this environment is public your api is vulnerable.

Post a Comment for "How Can I Retrieve A Service Account Oauth2 Token From Google Api With Javascript?"