Laravel Socialite令牌刷新

7
通过Socialite获取的access_token(通过Socialite::driver(self::PROVIDER)->user())具有有限的有效期限。对于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);

一个小时后,当令牌失效时,谷歌API开始返回401未经授权,并将其传播出去:

(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帐户,这很烦人。
谢谢!

1
还有一个后续问题:如果没有手动实现客户端,那么提供访问“refresh_token”的意义是什么? - rootpd
2个回答

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

这是我的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;
    }

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接