php - Laravel Socialite token 刷新

标签 php laravel laravel-socialite

Socialite(通过Socialite::driver(self::PROVIDER)->user())获取的access_token是有时间限制的,Google是一个小时.

我可以通过将重定向调用更改为以下方式来获取 refresh_token:

Socialite::driver(self::PROVIDER)->stateless()->with([
    'access_type' => 'offline',
])->redirect()

在一个小时内,我可以通过调用

根据 access_token 读取用户数据
// $token = read_stored_access_token()
\Socialite::driver(self::PROVIDER)->userFromToken($accessToken);

一个小时后,当 token 无效时,Google API 开始返回 401 Unauthorized 并且 Socialite 将其传播出去:

(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...)

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

真的是使用 Google 的 API 库并手动执行此操作的唯一方法吗?它不会扼杀使用 Socialite 的整个想法吗?

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

谢谢!

最佳答案

这是我通过离线访问从 Socialite 中保存用户的方法:

            $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();

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

    /**
     * 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;
    }

关于php - Laravel Socialite token 刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45035629/

相关文章:

php - 尝试散列密码时将空值输入到数据库中

php - print_r 未在浏览器中正确格式化输出

laravel - 如果 Laravel 中存在图像,如何避免编辑表单中需要图像?

php - 将函数调用放在 foreach 循环中与将结果放在变量中有区别吗?

PHP LoginScript MySQL 检查结果错误

php - Laravel schedule - 每小时,每天 - 了解何时开始

php - 具有正确 URL 的 Laravel 渲染 View

laravel-5 - AbstractProvider.php 第 200 行中的 Laravel Socialite InvalidStateException

php - Laravel Socialite 中的 Google 登录是否包含用户的电话号码?

php - 在 laravel 5 上使用 Socialite-package 进行 Linkedin 登录