Home > OS >  go through browser auth with rest requests - Gmail API
go through browser auth with rest requests - Gmail API

Time:12-03

I would like to send email messages with our corporate emails provided by Gmail. In order to do that, I would like to use Gmail API with rest commands (basically launched with a php procedural code, for legacy purpose).

I have that code :

I go to this url :

// https://accounts.google.com/o/oauth2/auth?client_id=my_client_id&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/gmail.send&response_type=code
// and obtain a token like that : 4/1AX4XfWgmW0ZdxXpJn8YzkVeDs3oXZUHyJcR7abE2TuqQrcmo4c1W02ALD4I

/*
echo GoogleAuthCurl("GET", '', array(
    'client_id' => $GOOGLE_CLIENT_ID, 
    'redirect_uri'=>'urn:ietf:wg:oauth:2.0:oob',
    'scope' => 'https://www.googleapis.com/auth/gmail.send',
    'response_type' => 'code'
    ), array()); 

then I can use requests in curl for getting my access 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 */

$tokenJson = json_decode( GoogleTokenCurl("POST", '', array(), array(
    'code' => '4/1AX4XfWiEWngRngF7qryjtkcOG1otVtisYpjHnej1E54Pujcrchef8REvdt0', 
    'client_id' => $GOOGLE_CLIENT_ID,
    'client_secret' => $GOOGLE_CLIENT_SECRET,
    'redirect_uri'=>'urn:ietf:wg:oauth:2.0:oob',
    'grant_type' => 'authorization_code'
    )
)); 

print_r($tokenJson); 

This far, I've got food for my authorization header. My issue is in the first step (with the consent asked to user). I wish i can do this step without putting my url in the browser, validate two screens to grant access before getting the authorization code.

I'm also interested in advices to create gmail messages with rest requests driven by curl. I found postman collection about all actions gmail api can do, but one or two call examples wouldn't do harm ;)

thanks !

CodePudding user response:

In the current state, by the method you are using, &response_type=code, you need two calls to the OAuth client to get the access token. You can find an example of how to handle it just using HTTP/REST requests here.

In any case, you could use Google API Client Library for PHP. Allows you to handle the OAuth authentication flow, only needing one interaction to get the token.

You can find a full example on how this works here, notice that this example uses the Drive API, if you want to use it within the Gmail API, you can check Gmail API PHP library.

Documentation:
  • Related