w3resource

Laravel (5.7) Laravel Socialite

Introduction

Ever wondered how you can make your application to authenticate users aside using the traditional login form? I have and good thing is Laravel Socialite. Socialite provides us with a very simple and convenient way to authenticate with OAuth providers. It currently supports authentication with Facebook, Twitter, LinkedIn, Google, GitHub, GitLab and Bitbucket.

There are adapters for other platform, these are listed at the community driven https://socialiteproviders.netlify.com/

Upgrading Socialite

When you want to upgrade to a new major version of Socialite, reviewing the socialite upgrade guide is very important.

Installation

If you want to get started with Socialite, you should use Composer to add the package to your project's dependencies:

composer require laravel/socialite

Configuration

Before you use Socialite, you need to also add credentials for the OAuth services your application utilizes. These credentials have to be placed in your config/services.php configuration file, and must use the key facebook, twitter, linkedin, google, github, gitlab or bitbucket, depending on the providers that your application requires. For instance:

'github' => [
    'client_id' => env('GITHUB_CLIENT_ID'),
    'client_secret' => env('GITHUB_CLIENT_SECRET'),
    'redirect' => 'http://your-callback-url',
],

Hint: If your redirect option contains a relative path, it is automatically resolved to a fully qualified URL.

Routing

Next, you can now authenticate users! You need two routes: one is for redirecting the user to the OAuth provider, and the other is for receiving the callback from the provider after authentication. We access Socialite by using the Socialite facade:

<?php

namespace App\Http\Controllers\Auth;

use Socialite;

class LoginController extends Controller
{
    /**
     * Redirects the user to the GitHub authentication page.
     *
     * @return \Illuminate\Http\Response
     */
    public function redirectToProvider()
    {
        return Socialite::driver('github')->redirect();
    }

    /**
     * Obtains the user information from GitHub.
     *
     * @return \Illuminate\Http\Response
     */
    public function handleProviderCallback()
    {
        $user = Socialite::driver('github')->user();

        // $user->token;
    }
}

The redirect method will take care of sending the user to the OAuth provider, while the user method reads the incoming request and retrieve the user's information from the provider.

You need to define routes to your controller methods:

Route::get('login/github', 'Auth\LoginController@redirectToProvider');
Route::get('login/github/callback', 'Auth\LoginController@handleProviderCallback');

Optional Parameters

Optional parameters in the redirect request is supported by a number of OAuth providers. If you want to include any optional parameters in the request, you should call the with method with an associative array:

return Socialite::driver('google')
    ->with(['hd' => 'example.com'])
    ->redirect();

Warning: When you use the with method, you should be careful not to pass any reserved keywords such as state or response_type.

Access Scopes

Before you redirect the user, you can also add additional "scopes" on the request using the scopes method. This method merges all existing scopes with the ones you supply:

return Socialite::driver('github')
    ->scopes(['read:user', 'public_repo'])
    ->redirect();

You can overwrite all existing scopes with the use of the setScopes method:

return Socialite::driver('github')
    ->setScopes(['read:user', 'public_repo'])
    ->redirect();

Stateless Authentication

The stateless method can be used to disable session state verification. This is useful when ou are adding social authentication to an API:

return Socialite::driver('google')->stateless()->user();

Retrieving User Details

After you have a user instance, you can then grab a few more details about the user:

$user = Socialite::driver('github')->user();

// OAuth Two Providers
$token = $user->token;
$refreshToken = $user->refreshToken; // not always provided
$expiresIn = $user->expiresIn;

// OAuth One Providers
$token = $user->token;
$tokenSecret = $user->tokenSecret;

// All Providers
$user->getId();
$user->getNickname();
$user->getName();
$user->getEmail();
$user->getAvatar();

Retrieving User Details From A Token (OAuth2)

If you already have a valid access token for a particular user, you can retrieve their details with the use of the userFromToken method:

$user = Socialite::driver('github')->userFromToken($token);

Retrieving User Details From A Token And Secret (OAuth1)

If you already have a valid pair of token / secret for a particular user, you can retrieve their details with the use of the userFromTokenAndSecret method:

$user = Socialite::driver('twitter')->userFromTokenAndSecret($token, $secret);


Follow us on Facebook and Twitter for latest update.