3

I am trying to make an authorize request with google oAuth using the code below

$client = new Google_Client();
$client->setClientId('qweqweqweqwe');
$client->setClientSecret('vQWsd1Geweqweqweqwe');
$client->setRedirectUri('http://localhost/test1');

$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setScopes(['https://www.googleapis.com/auth/gmail.readonly']);

if (request()->has('code')) {

    $credentials = $client->authenticate(request('code'));

    dd($credentials);

}

its working, but my question is: Is there any way to add user id on the request and get it back on callback ?

PrStandup
  • 313
  • 1
  • 4
  • 14

2 Answers2

3

A very good point on adding that param is preventing csrf attacks also.

The way how you add a param on google authorization request and then get back the param on the callback request from google, is by setting a base64 encoded json payload:

Before generating the Authorization url first off include the two functions to encode and decode the url params, simple:

public function base64UrlEncode($inputStr)
{
    return strtr(base64_encode($inputStr), '+/=', '-_,');
}


public function base64UrlDecode($inputStr)
{
    return base64_decode(strtr($inputStr, '-_,', '+/='));
}

Making the oauth request to google, make url params example:

$params = base64UrlEncode('{ "a" : "b" , "c" : 1 }');

In Google Client class there is a function setState($state) that you need to call before creating the url and pass the $params as parameters like:

$client = new Google_Client();
$client->setClientId('qweqweqweqwe');
$client->setClientSecret('vQWsd1Geweqweqweqwe');

$params = base64UrlEncode('{ "a" : "b" , "c" : 1 }');
$client->setState($params);

$client->setRedirectUri('http://localhost/test1');

Then the response will have state request param so in the callback route do:

Route::get('/callback', function(){


  $state = request()->get('state');    // GET['state'];
  $state = base64_decode(strtr($state, '-_,', '+/='));
  dd($state); // will output your params 
});

This answer somewhat based from: here

Leo
  • 7,274
  • 5
  • 26
  • 48
1

You can use state to send custom parameters with Google_Client::setState().

When setting up your Client:

$client = new Google_Client();
$client->setClientId('qweqweqweqwe');
$client->setClientSecret('vQWsd1Geweqweqweqwe');
$client->setRedirectUri('http://localhost/test1');
$client->setState('test=value');

And on callback, the parameters will be in state through GET:

var_dump($_GET["state"]); // test=value

You can send pretty much whatever you want, so try json_encode() or url_encode()ing your data if it gets too complex.

ishegg
  • 9,685
  • 3
  • 16
  • 31