【问题标题】:How to add a param to google oauth 2如何将参数添加到 google oauth 2
【发布时间】:2018-02-21 20:04:42
【问题描述】:

我正在尝试使用以下代码向 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);

}

它可以工作,但我的问题是:有没有办法在请求中添加用户 ID 并在回调中取回它?

【问题讨论】:

    标签: php laravel google-api google-oauth google-api-php-client


    【解决方案1】:

    添加该参数的一个很好的一点是还可以防止 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, '-_,', '+/='));
    }
    

    向google发出oauth请求,制作url参数示例:

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

    在 Google 客户端类中有一个函数 setState($state),您需要在创建 url 之前调用它并将 $params 作为参数传递,例如:

    $client = new Google_Client();
    $client->setClientId('qweqweqweqwe');
    $client->setClientSecret('vQWsd1Geweqweqweqwe');
    
    $params = base64UrlEncode('{ "a" : "b" , "c" : 1 }');
    $client->setState($params);
    
    $client->setRedirectUri('http://localhost/test1');
    

    然后响应将有状态请求参数所以在回调路由中做:

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

    这个答案有点基于: here

    【讨论】:

    • @ishegg 那里的解释不包括特定代码作为此答案。所以这个答案比那个更有用。
    • 也许可以,但您需要注明出处。
    【解决方案2】:

    您可以使用state 通过Google_Client::setState() 发送自定义参数。

    设置客户端时:

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

    并且在回调时,参数将通过 GET 在state

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

    您几乎可以发送任何您想要的东西,所以如果数据太复杂,请尝试json_encode()url_encode() 发送您的数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-06
      • 2019-08-23
      • 2021-08-24
      • 2017-05-30
      • 1970-01-01
      相关资源
      最近更新 更多