How can I manage OAuth refresh tokens with Laravel? How can I manage OAuth refresh tokens with Laravel? laravel laravel

How can I manage OAuth refresh tokens with Laravel?


It's been a while since this question was last visited, and seeing that it is the first Google result, I'd like to say: This is now possible with Socialite.

When you redirect your users to Google, set access_type to offline with the with() method when redirecting, like this:

    return Socialite::driver('google')        ->scopes() // For any extra scopes you need, see https://developers.google.com/identity/protocols/googlescopes for a full list; alternatively use constants shipped with Google's PHP Client Library        ->with(["access_type" => "offline", "prompt" => "consent select_account"])        ->redirect();

This will make Google return a refresh token.


This is difficult to find information for, partially because of the OAuth2-server package for Laravel to provide its own OAuth solution which is most of the search results.

I think the best answer is going to be writing your own YoutubeProvider for Socialite. Here's a tutorial: https://medium.com/laravel-news/adding-auth-providers-to-laravel-socialite-ca0335929e42#.6bn8i2wz4

It will be a pain to change Socialite to start working with refresh tokens, so I think the best route will be for the YoutubeProvider to have an additional call to a new getRefreshToken function at the end of the existing getAccessToken function. Change both the access and refresh tokens to save the retrieved token to the database, because Socialite will not give you the option to access the refresh token to save it in a helper/controller class.

Create a Tokens model and database table, and store both access and refresh tokens in there with a relationship to a User model.

When you write your YoutubeService helper, it will need to be able to attempt an API call with an access token and know to refresh it with the refresh token if it receives the error message that it's expired/invalid.

The Google's API library for PHP seems to handle this automatically with $client->setAccessType("offline"): https://developers.google.com/api-client-library/php/auth/web-app

but as soon as you start needing refresh tokens for something other than Google, you'll be writing that code anyway if the new provider doesn't also have a library. On the upside, this library has a Service specifically for Youtube, so it should handle all the API calls to Youtube that you may need. I am not sure entirely how using this library will mesh with Socialite, since Socialite seems to already do a lot of what this library does. You might wind up making some sort of redundant authorization within your YoutubeService class unless you really want to start customizing things.

It might be worth considering removing Socialite from the equation entirely and using Google's library when it comes to their services.