Laravel 5.1 - 通过 Socialite 进行 Facebook 身份验证

sen*_*nty 5 facebook facebook-graph-api laravel laravel-socialite

我正在尝试在我的项目中实施 Facebook 登录,但收到错误:

Middleware.php 第 69 行中的 ClientException:客户端错误:400

  1. 在 /Applications/MAMP/htdocs/laratest/vendor/guzzlehttp/guzzle/src/Middleware.php 第 69 行

  2. 在 Promise.php 中的 Middleware::GuzzleHttp{closure}(object(Response)) 第 199 行

  3. 在 Promise.php 第 152 行中的 Promise::callHandler('1', object(Response), array(object(Promise), object(Closure), null))

  4. 在 TaskQueue.php 中的 Promise::GuzzleHttp\Promise{closure}() 第 60 行

  5. 在 CurlMultiHandler.php 第 96 行的 TaskQueue->run() 处


我经历过的步骤:

  • composer require laravel/socialitecomposer update

  • 在我的config>services.app中,

'facebook' => [ 'client_id' => env('FB_CLIENT_ID'), 'client_secret' => env('FB_SECRET_ID'), 'redirect' => 'http://localhost.com:8888', ],

  • config>app.php中添加 Laravel\Socialite\SocialiteServiceProvider::class,&'Socialite' => Laravel\Socialite\Facades\Socialite::class,

  • 路由设置成功。

Route::get('auth/facebook', 'Auth\AuthController@redirectToProvider'); Route::get('auth/facebook', 'Auth\AuthController@handleProviderCallback');

  • 在我的刀片文件中成功设置链接。Login with Facebook

  • 在我的Controller>AuthController.php中,我添加了:

    use Laravel\Socialite\Facades\Socialite;
    
    ** Beside everything that AuthController has, inside the AuthController class, I added:**
    
      public function redirectToProvider()
       {
        return Socialite::driver('facebook')
             ->scopes(['scope1', 'scope2'])->redirect();
       }
    
    /**
     * Obtain the user information from Facebook.
     *
     * @return Response
     */
    
       public function handleProviderCallback()
        {
          $user = Socialite::driver('facebook')->user();
    
        // $user->token;
        }
    
    Run Code Online (Sandbox Code Playgroud)
  • 还有用户表:

       public function up()
        {
           Schema::create('users', function (Blueprint $table) {
              $table->increments('id');
              $table->string('username');
              $table->string('name');
              $table->string('email')->unique();
              $table->string('password', 60);
              $table->string('avatar');
              $table->string('provider');
              $table->string('provider_id');
              $table->rememberToken();
              $table->timestamps();
                });
        }
    
    Run Code Online (Sandbox Code Playgroud)

编辑: 当我注释掉$user = Socialite::driver('facebook')->user();部分时,我被重定向到localhost.com/auth/facebook

编辑2: 我的.env文件:

'facebook' => [ FB_CLIENT_ID => '###', FB_SECRET_ID => 'this-is-secret!', ],

Fra*_*ri7 3

我认为你的两个路由不应该有相同的 URL,因为 Laravel 无法知道使用哪个。

Facebook 返回一个 ?code 参数,因此请利用它!如果包含 ?code,则处理来自 Socialite 的登录逻辑,如果不包含,则重定向到 Facebook。

您的代码中有两个未知范围,scope1 和scope2,Facebook 不知道这些范围,并且在尝试访问它们时将返回错误。使用像 public_profile 或 email 这样的真实范围,你应该已经设置好了。(范围是您请求的权限)