PrS*_*dup 4 php google-api laravel google-oauth google-api-php-client
我正在尝试使用下面的代码向 google oAuth 发出授权请求
$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);
}
Run Code Online (Sandbox Code Playgroud)
它的工作原理,但我的问题是:有什么方法可以在请求中添加用户 ID 并在回调中取回它吗?
添加该参数的一个非常好的一点是还可以防止 csrf 攻击。
如何在 google 授权请求上添加参数,然后从 google 获取回调请求上的参数,方法是设置base64编码的 json 有效负载:
在生成授权 url 之前,首先包含两个函数来对 url 参数进行编码和解码,很简单:
public function base64UrlEncode($inputStr)
{
return strtr(base64_encode($inputStr), '+/=', '-_,');
}
public function base64UrlDecode($inputStr)
{
return base64_decode(strtr($inputStr, '-_,', '+/='));
}
Run Code Online (Sandbox Code Playgroud)
向 google 发出 oauth 请求,制作 url 参数示例:
$params = base64UrlEncode('{ "a" : "b" , "c" : 1 }');
Run Code Online (Sandbox Code Playgroud)
setState($state)在 Google Client 类中,您需要在创建 url 之前调用一个函数并传递$paramsas 参数,例如:
$client = new Google_Client();
$client->setClientId('qweqweqweqwe');
$client->setClientSecret('vQWsd1Geweqweqweqwe');
$params = base64UrlEncode('{ "a" : "b" , "c" : 1 }');
$client->setState($params);
$client->setRedirectUri('http://localhost/test1');
Run Code Online (Sandbox Code Playgroud)
然后响应将具有状态请求参数,因此在回调路由中执行以下操作:
Route::get('/callback', function(){
$state = request()->get('state'); // GET['state'];
$state = base64_decode(strtr($state, '-_,', '+/='));
dd($state); // will output your params
});
Run Code Online (Sandbox Code Playgroud)
这个答案有点基于: 这里