如何使用社交网站google驱动程序从谷歌获取用户数据

问题描述 投票:0回答:2

我正在尝试使用laravel谷歌社交网站驱动程序,我需要使用访问令牌从谷歌获取用户数据,我从我的api电话。但是当我以为我已经完成了所有事情时,它会给出一个错误,说Call to protected method Laravel\\Socialite\\Two\\GoogleProvider::getUserByToken()

我明白它的说法我无法访问该方法,因为它的保护。那么如何解决这个问题呢。

我的目标

我的目标是验证我从我的移动应用程序获取的社交访问(基本上是谷歌)令牌,并将该微粒用户的用户数据存储到我从api.php的社交网站My Route收到的数据库中

Route::post('login','api\unAuthApiCall@index');

我的控制器

namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Laravel\Socialite\Facades\Socialite;


class unAuthApiCall extends Controller
{
    //Get the authentication token
    public function index(Request $request){

        //get the auth token
        $authToken= Input::get('auth_token');

        //Validate authtoken with google and get user's data
        $driver = Socialite::driver('google');

        $socialUserObject= $driver->getUserByToken($authToken);

        return json_encode($socialUserObject);
    }
}

我得到的回应

{
    "message": "Call to protected method Laravel\\Socialite\\Two\\GoogleProvider::getUserByToken() from context 'App\\Http\\Controllers\\api\\unAuthApiCall'",
    "exception": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",
    "file": "C:\\Users\\CODED\\Documents\\laravelSocilte\\app\\Http\\Controllers\\api\\unAuthApiCall.php",
    "line": 28,
    "trace": [
        {
            "function": "index",
            "class": "App\\Http\\Controllers\\api\\unAuthApiCall",
            "type": "->"
        }
laravel oauth-2.0 google-api laravel-5.5 laravel-socialite
2个回答
2
投票

经过一番长时间的研究,并在这里和那里检查代码。我发现了修复。这并不复杂,显然我发现我使用了错误的方法。这是正确的代码

$token =Input::get('auth');
$provider='google';
$driver= Socialite::driver($provider);
$socialUserObject = $driver->userFromToken($token);
print_r('$socialUserObject');

这将给出完整的用户对象。


0
投票

这对我行得通

路线

Route::get('/redirect/{provider}', 'Auth\SocialAuthController@redirect');
Route::get('/auth/facebook/callback', 'Auth\SocialAuthController@callback');
Route::get('/auth/google/callback', 'Auth\SocialAuthController@callback');

调节器

<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Laravel\Socialite\Facades\Socialite;

class SocialAuthController extends Controller
{
  protected $driver = ['facebook', 'google'];

  public function redirect($provider)
  {
    if(!in_array($provider, $this->driver)){

        abort(400);
    }

    return Socialite::driver($provider)->redirect();
  }

  public function callback(Request $request)
  {
    $provider = $request->segment(2);

    if(!in_array($provider, $this->driver)){

        abort(400);
    }

    $user = Socialite::driver($provider)->user();

    //save the user or do something else

    auth()->login($user);

    return redirect()->to('/');
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.