Search code examples
laraveltokenlaravel-socialite

Socialite refresh tokens


I'm building a Laravel application where I need a user to be able to connect social channels, such as Twitter, Twitch, YouTube etc. I don't need them to be able to login with these medias, but connect them, so I my application can get access token to retrieve information from their social channels.

I started working on connecting Twitch using Socialite, but I noticed their token expires and that I'm receiving a refresh_token as well.

I followed Socialites advice regarding handling invalid tokens, rather than keeping an eye on when it expires. The issue I ran into though is.. How do I refresh the token with socialite? I don't seem to be able to find a method, where I can get a new token from the refresh_token.

Can anyone tell me if this is even build into Socialite or if I have to build it myself or even use something else than Socialite?


Solution

  • Refreshing tokens is not up to Laravel Socialite.

    This is something you do on the authorization server.

    In case of Twitch, see: https://dev.twitch.tv/docs/authentication/refresh-tokens/

    Every Socialite Provider has its own endpoints. But they all should follow the OAuth2 RFC

    In Laravel, you can use Guzzle like so:

    $http = new GuzzleHttp\Client;
    
    $response = $http->post('https://id.twitch.tv/oauth2/token', [
        'form_params' => [
            'grant_type'    => 'refresh_token',
            'refresh_token' => '<your refresh token>',
            'client_id'     => '<your client ID>',
            'client_secret' => '<your client secret>',
            'scope' => '',
        ],
    ]);
    
    return json_decode((string) $response->getBody(), true);
    

    P.s. After a quick look, it seems you can retrieve this URL dynamically using the getAuthUrl() method in \SocialiteProviders\Twitch\Provider, but this is not in the Contract...