Creating Google Cloud API app and Setting up OAuth2.0

Hi Postman lovers :wave:

As I found setting up OAuth2.0 for Google API can be a bit tricky for newbies like me so I created a collection which walks through steps to create Google app and setting up OAuth2.0 to be able to get access token using Postman Authorization Helper.

Collection: Postman

Hope this is useful :slightly_smiling_face:

2 Likes

Much love to you!
I was searching for exactly this, a straight-forward, simple to follow tutorial.

Thank you very much!

Argh, I was celebrating too early :smiley:

The token expires after 1 hour and all the instructions I found are not nearly as good as yours was.

Does anyone/@taehoshino have a clear idea how to get the refresh token in Postman?

@florian

This is an example using a pre-request script to login to Microsoft.

pm.test("Check for collectionVariables", function () {
    let vars = ['clientId', 'clientSecret', 'tenantId', 'username', 'password', 'scope'];
    vars.forEach(function (item, index, array) {
        console.log(item, index);
        pm.expect(pm.collectionVariables.get(item), item + " variable not set").to.not.be.undefined;
        pm.expect(pm.collectionVariables.get(item), item + " variable not set").to.not.be.empty; 
    });

    if (!pm.collectionVariables.get("bearerToken") || Date.now() > new Date(pm.collectionVariables.get("bearerTokenExpiresOn") * 1000)) {
        pm.sendRequest({
            url: 'https://login.microsoftonline.com/' + pm.collectionVariables.get("tenantId") + '/oauth2/v2.0/token',
            method: 'POST',
            header: 'Content-Type: application/x-www-form-urlencoded',
            body: {
                mode: 'urlencoded',
                urlencoded: [
                    { key: "client_id", value: pm.collectionVariables.get("clientId"), disabled: false },
                    { key: "scope", value: pm.collectionVariables.get("scope"), disabled: false },
                    { key: "username", value: pm.collectionVariables.get("username"), disabled: false },
                    { key: "password", value: pm.collectionVariables.get("password"), disabled: false },                    
                    { key: "client_secret", value: pm.collectionVariables.get("clientSecret"), disabled: false },
                    { key: "grant_type", value: "password", disabled: false },
                ]
            }
        }, function (err, res) {
            if (err) {
                console.log(err);
            } else {
                pm.test("Status code is 200", () => {
                    pm.expect(res).to.have.status(200);
                });
                let resJson = res.json();
                pm.collectionVariables.set("bearerTokenExpiresOn", resJson.expires_in);
                pm.collectionVariables.set("bearerToken", resJson.id_token);
            }
        });
    }
});

However, looking at a few articles on the subject. Even though this works for me, it’s basically getting a new ID token each time. It’s not using a refresh token. As I’m not testing the login per se, this is ok for my circumstances. It might not be for yours.

If you really want it to replicate how an application should work, then the following resources may explain the differences.

Access token vs Refresh token in OAUTH2 | by Donald Le | Medium

AccessToken Vs ID Token Vs Refresh Token - What? Why?When? (c-sharpcorner.com)

OAuth 2.0 Refresh Token Best Practices (fusebit.io)

For this to work properly and mimic a real application, it looks like you should have something similar to the code I detailed above but with an if statement that requests a new token if the collection variable used to store the token is blank, but a slightly different sendRequest if requesting just a refresh token.

I can’t remember seeing any example of using refresh codes properly, when I originally set all this up for our purposes which was only a couple of months ago. All of the examples were getting a new access token each and every time.

I just had another look at what the Microsoft login API actually returns.

It tells me the token type, which is “Bearer” (which is usually for Access_Tokens).

I get an Access_Token and an ID_Token (which I understand is what OAuth2.0 recommends for compatibility), but no refresh token.

The Access_Token doesn’t appear to give access to the resource. The ID_Token does. (I only need to include the ID_Token in the header called Bearer for the subsequent request to the Azure web app to work).

I get an expiry date for both elements, but they are set to the same date. As far as I can tell, it does not provide me with a refresh token. Both tokens are reasonably short lived.

@vegconomist

When you send the request in Postman, it should show you the response in the log. Does it actually include a refresh token when you authenticate to Google?

It might be slightly different for Microsoft as the authentication details provided above is direct access to the login API as recommended by Microsoft so that you don’t get recognised as an automated login and blocked.

Hi @michaelderekjones

Thank you for looking into this so deeply!

Actually, I only get this as a result, so no refresh token included…
But since it expires in 60 minutes, there has to be a way to refresh it, right? Otherwise, how could I run the requests repeatedly without having to manually authenticate again.

{
  "access_token": "ya29.a0AeTM1XXXXXXXXXXXXXX",
  "expires_in": 3594,
  "scope": "https://www.googleapis.com/auth/spreadsheets.readonly",
  "token_type": "Bearer"
}

@vegconomist

That is where I would use the pre-request script example above.

Pre-request scripts run before every request. You can decide whether to put it at the collection level or just the individual request.

The script does have some logic and won’t just get a new token every time. It has an IF statement checking the expires_in time.

Therefore, I suspect this will work ok in your circumstance.