簡體   English   中英

Laravel Socialite 令牌刷新

[英]Laravel Socialite token refreshing

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

一個小時后,當令牌無效時,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();

這是我的令牌刷新解決方案。 我通過在我的用戶模型中為令牌屬性創建訪問器來實現它:

    /**
     * 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;
    }
return Socialite::driver('google')
    ->scopes() 
    ->with(["access_type" => "offline", "prompt" => "consent select_account"])
    ->redirect();

默認情況下,refresh_token 僅在第一次授權時返回,通過添加“prompt”=>“consent select_account”,我們強制每次都返回它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM