Laravel Socialite 令牌刷新

roo*_*tpd 6 php laravel laravel-socialite

access_token由社会名流收购(通过Socialite::driver(self::PROVIDER)->user()具有有限的时间有效性。对于谷歌这是一个小时。

我可以refresh_token通过将重定向调用更改为:

Socialite::driver(self::PROVIDER)->stateless()->with([
    'access_type' => 'offline',
])->redirect()
Run Code Online (Sandbox Code Playgroud)

一个小时内,我可以access_token通过调用读取用户数据

// $token = read_stored_access_token()
\Socialite::driver(self::PROVIDER)->userFromToken($accessToken);
Run Code Online (Sandbox Code Playgroud)

一小时后,当令牌失效时,Google API 开始返回401 Unauthorized,Socialize 将其传播出去:

(1/1) ClientException
Client error: `GET https://www.googleapis.com/plus/v1/people/me?prettyPrint=false` resulted in a `401 Unauthorized` response:
{"error":{"errors":[{"domain":"global","reason":"authError","message":"Invalid Credentials","locationType":"header","loc (truncated...)
Run Code Online (Sandbox Code Playgroud)

现在有了refresh_token,我应该可以轻松刷新了access_token。但是我在 Socialize 文档或源代码中找不到允许我这样做的提及。

真的是唯一的方法来完成这个使用谷歌的 API 库并手动执行此操作吗?它不会扼杀使用 Socialize 的整个想法吗?

注意:我试图避免redirect()再次拨打电话,因为这可能会迫使用户每小时选择一个他的 Google 帐户,这很烦人。

谢谢!

Arm*_*092 5

以下是我通过离线访问从社交名流中保存用户的方法:

            $newUser                       = new User;
            $newUser->name                 = $user->name;
            $newUser->email                = $user->email;
            $newUser->google_id            = $user->id;
            $newUser->google_token         = $user->token;
            $newUser->token_expires_at     = Carbon::now()->addSeconds($user->expiresIn);
            $newUser->google_refresh_token = $user->refreshToken;
            $newUser->avatar               = $user->avatar;
            $newUser->avatar_original      = $user->avatar_original;
            $newUser->save();
Run Code Online (Sandbox Code Playgroud)

这是我的令牌刷新解决方案。我通过在我的用户模型中为令牌属性创建访问器来实现它:

    /**
     * Accessor for google token of the user
     * Need for token refreshing when it has expired
     *
     * @param $token
     *
     * @return string
     */
    public function getGoogleTokenAttribute( $token ) {
        //Checking if the token has expired
        if (Carbon::now()->gt(Carbon::parse($this->token_expires_at))) {
            $url  = "https://www.googleapis.com/oauth2/v4/token";
            $data = [
                "client_id"     => config('services.google.client_id'),
                "client_secret" => config('services.google.client_secret'),
                "refresh_token" => $this->google_refresh_token,
                "grant_type"    => 'refresh_token'
            ];

            $ch = curl_init($url);

            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            $result = curl_exec($ch);
            $err    = curl_error($ch);

            curl_close($ch);

            if ($err) {
                return $token;
            }
            $result = json_decode($result, true);

            $this->google_token     = isset($result['access_token']) ? $result['access_token'] : "need_to_refresh";
            $this->token_expires_at = isset($result['expires_in']) ? Carbon::now()->addSeconds($result['expires_in']) : Carbon::now();
            $this->save();

            return $this->google_token;

        }

        return $token;
    }
Run Code Online (Sandbox Code Playgroud)


Sai*_*han 2

return Socialite::driver('google')
    ->scopes() 
    ->with(["access_type" => "offline", "prompt" => "consent select_account"])
    ->redirect();
Run Code Online (Sandbox Code Playgroud)

默认情况下,refresh_token 仅在第一次授权时返回,通过添加“prompt”=>“consent select_account”我们强制每次都返回它。