How to Integrate Laravel Passport with Social Authentication Providers

April 08, 2025
Written by
Lucky Opuama
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by

How to Integrate Laravel Passport with Social Authentication Providers

Most systems today require authentication to access their resources, ensuring only authenticated users can interact with sensitive data. As security becomes a top priority, integrating strong authentication techniques like OAuth or API token-based authentication is very important.

In this tutorial, you will learn how to use Laravel Passport alongside Laravel Socialite and several common social authentication providers to enhance user authentication in Laravel. By combining Passport's token-based authentication with Socialite's integration of popular social services, you can provide a smooth login experience while maintaining strict security standards.

Prerequisite

What is Laravel Passport?

Laravel Passport is an OAuth 2.0 server implementation that simplifies API authentication in Laravel applications. It allows you to easily set up token-based authentication, enabling secure access to APIs. With Laravel Passport, you can easily handle the issuance, management, and validation of access tokens, making it simple to authenticate API requests and manage secure communication between clients and servers.

Let’s get started!

Scaffold a basic Laravel project

We'll start by creating a new Laravel project and change into the new project directory. To do so, run the following command:

composer create-project laravel/laravel social-auth
cd social-auth

Now, check if your application was successfully installed by running the following command in your terminal to launch the development server.

php artisan serve

Once the server is running, open your preferred web browser and visit the following URL: http://127.0.0.1:8000. You should see a page similar to the one shown below.

Integrate Laravel Passport and Laravel Socialite

This hybrid approach simplifies managing social logins and securing API access by combining Laravel Passport with Laravel Socialite.

If the goal is to implement social authentication without API tokens or OAuth2, use Laravel Socialite. For a detailed guide, check out this Twilio blog post.

Here’s a quick breakdown of the two packages:

  • Laravel Passport: This manages secure API token generation and OAuth2 for authenticated users
  • Laravel Socialite: This handles user authentication through social platforms (such as Facebook, Google, and Discord)

To install Laravel Passport, run the command below in a new terminal tab or session:

php artisan install:api --passport

This command will set up all the necessary configurations for Passport. During the installation, you’ll be prompted with a question in the terminal asking whether you would like to use UUIDs as the primary keys. Just type "no" to proceed with the default setup.

Now, install Laravel Socialite by running the following command:

composer require laravel/socialite

Configure the installed packages

Now, you can proceed with configuring Laravel Passport. Navigate to the app/Models directory, open the User.php file, and add the HasApiTokens trait to the class, as exemplified in the following code example

use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    // … remaining code
}

The traits in this code perform the following functions:

  • HasApiTokens: This trait allows the User model to issue, manage, and authenticate API tokens for OAuth2-based API authentication
  • HasFactory: This trait enables the User model to easily generate fake or factory data for testing purposes using Laravel factories
  • Notifiable: This trait allows the User model to receive notifications, such as emails or SMS, by providing methods for routing notifications to the user

Next, navigate to the config directory, open the auth.php file, and add the following code:

'guards' => [
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

This code will instruct your application to use Passport's Token Guard when authenticating incoming API requests.

Next, open your .env file and add the following configurations:

FACEBOOK_CLIENT_ID=<FACEBOOK_CLIENT_ID>
FACEBOOK_CLIENT_SECRET=<FACEBOOK_CLIENT_SECRET>
FACEBOOK_REDIRECT=http://localhost:8000/api/auth/facebook/callback
GOOGLE_CLIENT_ID=<GOOGLE_CLIENT_ID>
GOOGLE_CLIENT_SECRET=<GOOGLE_CLIENT_SECRET>
GOOGLE_REDIRECT=http://localhost:8000/api/auth/google/callback
DISCORD_CLIENT_ID=<DISCORD_CLIENT_ID>
DISCORD_CLIENT_SECRET=<DISCORD_CLIENT_SECRET>
DISCORD_REDIRECT=http://localhost:8000/api/auth/discord/callback

Next, configure Laravel Socialite to integrate with three social platforms: Facebook, Google, and Discord. But first, you'll need the client ID and client secret from these platforms. Follow the steps below to obtain them.

For Facebook:

Visit Facebook Developers, login with your Facebook account, and click on My Apps button at the top-right corner of your screen. This will direct you to the dashboard. Next, click the Create App button to begin setting up your app.

Under App name, enter a name for your application, then click the Next button to continue.

The Meta Create an app form, showing the App details section.

When prompted to select a use case for your application, choose Authenticate and request data from users with Facebook Login, and then click Next.

The "Authenticate and request data from users with Facebook Login" option enabled in the Meta/Facebook app setup process.

Ignore the next prompt, as this app is not intended for business purposes. Click Next to continue, and then click Go to Dashboard at the final prompt to complete the setup.

To configure valid OAuth redirect URIs, go to Use Cases on the Dashboard, and click the Customize button.

Next, go to settings, then set the redirect URI under the Valid OAuth Redirect URIs section.

Setting value OAuth Redirect URIs in the Meta/Facebook app setup process.

Next, click Save changes.

After configuring the redirect URI, navigate to App Settings > Basic In your dashboard to retrieve your Client ID and Client Secret.

Basic App Settings in the Meta/Facebook app setup process.

For Google

Visit the Google Cloud Console, login, then go to Select a project.

Select a Google project

Next, click on New Project, enter a name of your choice, and then click Create.

New (Google) Project settings form showing the Project name filled out.

Next, click the menu icon, navigate to APIs & Services, and then select OAuth Consent Screen.

The Google Cloud main navigation showing a path from "APIs & Services" to "OAuth consent screen".

To enable the OAuth Consent Screen, select the External radio button, then click Create. Next, provide the necessary app information, which includes your App Name, User Support Email, and Developer Contact Information. then, click Save and Continue.

The Google APIs & Services OAuth consent screen, showing the "Edit app registration" form with the "App name" field filled out and the "User support email" field filled out but redacted.

For the remaining sections, click Save and Continue until you reach the Back to Dashboard button. On the APIs & Services section, go to Credentials, click Create Credentials, and select OAuth Client ID.

Then, set the Application Type to Web application and add your authorized redirect URIs.

The Credentials section of the Google APIs & Services form with the Application Type and Name filled out.

Click the CREATE button to generate your Client ID and Client Secret.

For Discord

Visit the Discord Developer Portal and login. Click New Application, enter a name for your application, and click Create.

In the sidebar, navigate to OAuth2 to view your client information.

The Discord OAuth2 configuration form.

Under OAuth2 Scopes, select the identify scope. In the Redirects section, add a redirect URI that will handle the callback in your Laravel application.

Finally, click Save and retrieve the Client ID and Client Secret.

Now that you have the necessary credentials, in .env replace the placeholders with your actual client ID and client secret. Then, go to the config directory, open the services.php file, and add the following code to the array returned in the file:

'facebook' => [
    'client_id' => env('FACEBOOK_CLIENT_ID'),
    'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
    'redirect' => env('FACEBOOK_REDIRECT'),
],

'google' => [
    'client_id' => env('GOOGLE_CLIENT_ID'),
    'client_secret' => env('GOOGLE_CLIENT_SECRET'),
    'redirect' => env('GOOGLE_REDIRECT'),
],

'discord' => [
    'client_id' => env('DISCORD_CLIENT_ID'),
    'client_secret' => env('DISCORD_CLIENT_SECRET'),
    'redirect' => env('DISCORD_REDIRECT'),
],

Modify the authentication flow

Modifying the authentication flow involves getting the user's login request, routing it to the social provider, managing the provider's callback, and creating a Passport token for safe interaction with the backend API. This connection provides a smooth and secure experience for a simplified login process. Let’s dive into the coding aspect properly.

Run the command below to generate a controller:

php artisan make:controller SocialAuthController

Next, navigate to app/Http/Controllers directory and open the SocialAuthController.php file. Replace the existing code with the following and save the changes:

<?php

namespace App\Http\Controllers;

use Laravel\Socialite\Facades\Socialite;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class SocialAuthController extends Controller
{
    public function redirectToProvider($provider)
    {
        return Socialite::driver($provider)->stateless()->redirect();
    }

    public function handleProviderCallback($provider)
    {
        $socialUser = Socialite::driver($provider)->stateless()->user();
        $user = User::where('email', $socialUser->getEmail())->first();
        if (!$user) {
            $user = User::create([
                'name' => $socialUser->getName(),
                'email' => $socialUser->getEmail(),
                'password' => Hash::make(uniqid()),
            ]);
        }
        $token = $user->createToken('SocialToken')->accessToken;

        return response()->json([
            'token' => $token,
            'user' => $user,
        ]);
    }
}

When you click the login button of any social provider, the redirectToProvider() method will redirect them to the provider's authentication page. After successfully authenticating, the provider will redirect you to your application's callback URL. The handleProviderCallback() method processes the returned social user data. If the user already exists, they are logged in; if not, a new user is created and a Passport access token is generated for them.

Add the routes

Routes are important for handling the redirection to the social provider and for managing the callback that the provider sends after successful authentication. To add the routes, navigate to the routes directory, open the api.php, and add the following code to the end of the file:

Route::get('auth/{provider}', [App\Http\Controllers\SocialAuthController::class, 'redirectToProvider']);
Route::get('auth/{provider}/callback', [App\Http\Controllers\SocialAuthController::class, 'handleProviderCallback']);
Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:api');

This code defines three routes:

  • The first route redirects the user to the chosen social provider for authentication
  • The second route handles the callback after the provider authenticates the user
  • The third route returns the authenticated user's data, and allows users to retrieve their profile information after successfully logging in

Create the frontend

To simplify the frontend development, the user interface will be built using React. Run the following commands to create a new React template and change into its directory:

npx create-react-app social-auth-app
cd social-auth-app

Add the required packages

The next thing to do is to install the required packages:

  • Axios: It is used to interact with your application backend (make HTTP requests)
  • React Router: It is used to handle the callback URL properly
  • Font Awesome: It is used for creating icons

To install them, run the following command:

npm install axios react-router-dom @fortawesome/react-fontawesome @fortawesome/free-brands-svg-icons

Create the social login component

Now that the React application is fully set up, navigate to the React app's src directory and create a new folder named components. Inside the components folder, create a new file called SocialLogin.js and add the following code:

import React from 'react';
import '../App.css';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faFacebook, faGoogle, faDiscord } from '@fortawesome/free-brands-svg-icons';

const SocialLogin = () => {
  const handleSocialLogin = (provider) => {
    window.location.href = `http://localhost:8000/api/auth/${provider}`;
  };
  return (
    <div className="social-login-container">
      <button
        onClick={() => handleSocialLogin('facebook')}
        className="social-btn facebook"
      >
        <FontAwesomeIcon icon={faFacebook} className="icon" /> Sign in with Facebook
      </button>
      <button
        onClick={() => handleSocialLogin('google')}
        className="social-btn google"
      >
        <FontAwesomeIcon icon={faGoogle} className="icon" /> Sign in with Google
      </button>
      <button
        onClick={() => handleSocialLogin('discord')}
        className="social-btn discord"
      >
        <FontAwesomeIcon icon={faDiscord} className="icon" /> Sign in with Discord
      </button>
    </div>
  );
};

export default SocialLogin;

The code provides a simple user interface with buttons to trigger the social login, as well as the handleSocialLogin() function, which redirects the browser to the backend URL for authentication through social providers.

Next, create a new file named SocialCallback.js inside the components folder and add the following code inside it:

import React, { useEffect } from 'react';
import axios from 'axios';
import { useNavigate, useLocation } from 'react-router-dom';

const SocialCallback = () => {
  const navigate = useNavigate();
  const location = useLocation();
  useEffect(() => {
    const fetchToken = async () => {
      const queryParams = new URLSearchParams(location.search);
      const provider = queryParams.get('provider');
      try {
        const { data } = await axios.get(
          `http://your-laravel-backend-domain/api/auth/${provider}/callback`
        );
        localStorage.setItem('token', data.token);
        navigate('/');
      } catch (error) {
        console.error('Error fetching token', error);
      }
    };
    fetchToken();
  }, [location, navigate]);
  return <div>Loading...</div>;
};

export default SocialCallback;

This code retrieves the OAuth provider from the URL, then sends a request to the backend to obtain the OAuth token and stores the token in local storage. After it successfully authenticates, it then redirects the user back to the homepage.

Next, update the App.css file (in the top-level of the React project's directory) to modify the appearance of your frontend using the code below.

.App {
  text-align: center;
}

.App-header {
  background: linear-gradient(135deg, #b493fb, #57c6f5);
  min-height: 50vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  animation: gradientAnimation 8s ease infinite;
  color: #fff;
}

.App-link {
  color: #61dafb;
}

@keyframes gradientAnimation {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

.social-login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 20px;
}

.social-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 250px;
  padding: 10px 15px;
  margin: 10px 0;
  border: none;
  border-radius: 5px;
  color: #fff;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: background-color 0.3s;
}

.social-btn img {
  width: 20px;
  height: 20px;
  margin-right: 10px;
}

.icon {
  margin-right: 15px;
  font-size: 20px;
}

.facebook {
  background-color: #3b5998;
}

.facebook:hover {
  background-color: #334d84;
}

.google {
  background-color: #db4437;
}

.google:hover {
  background-color: #c23321;
}

.discord {
  background-color: #5865f2;
}

.discord:hover {
  background-color: #4854c4;
}

Next, update the App.js file with the following code:

import React from 'react';
import './App.css';
import SocialLogin from './components/SocialLogin';
import SocialCallback from './components/SocialCallback';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

function App() {
  return (
    <Router>
      <div className="App">
        <header className="App-header">
          <h1>Social Authentication</h1>
        </header>
        <Routes>
          <Route path="/" element={<SocialLogin />} />
          <Route path="/auth/callback" element={<SocialCallback />} />
        </Routes>
      </div>
    </Router>
  );
}

export default App;

To enable communication between your React app and the Laravel backend, you need to configure the CORS (Cross-Origin Resource Sharing). To do this, run the following command in the project's top-level directory:

php artisan config:publish cors

This command will publish the cors configuration file in your Laravel application. Next, go to the config directory, open the cors.php file, and update the allowed_origins array to include your React application URL, like so:

'allowed_origins' => ['http://localhost:3000'],

Test the application

Since your Laravel application is already running, open a new terminal session or tab. Navigate to the social-auth-app directory where your React frontend is located, and start the application by running the following command:

npm start

Once the development server is up, the frontend should automatically open in your default browser. If it doesn't, you can manually navigate to http://localhost:3000 in your browser to access the frontend.

The social authentication window of the application.

Click on any of the social platform buttons to start the login process. After successfully authenticating, you'll receive a response similar to the image shown below, when the Google button is clicked.

Sign in with Google - Choose an account

Attempting to log in with Discord will result in an error because Laravel Socialite only supports a limited set of social login providers, as listed below:

  • Facebook
  • Twitter
  • Google
  • LinkedIn
  • GitHub
  • GitLab
  • Bitbucket

To enable Discord, you'll need to extend Socialite by adding the Discord provider. Follow these steps to do so:

Install the Required Packages

First, you need to install the socialiteproviders/manager package, which allows you to add custom providers. Run the following command in your terminal:

composer require socialiteproviders/manager

Next, install the Discord provider by running the command below:

composer require socialiteproviders/discord

Register the Discord Provider

To make Socialite recognize the Discord provider, you need to register it in your application. Navigate to the App\Providers directory and open the AppServiceProvider.php file. Then, update the file with the following code:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use SocialiteProviders\Manager\SocialiteWasCalled;
use SocialiteProviders\Discord\DiscordExtendSocialite;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        //
    }

    public function boot(): void
    {
        $this->app->make('events')->listen(SocialiteWasCalled::class, function (SocialiteWasCalled $socialiteWasCalled) {
            $socialiteWasCalled->extendSocialite('discord', \SocialiteProviders\Discord\Provider::class);
        });
    }
}

After implementing the changes, you should now be able to click on the Discord login option and authenticate successfully.

That's how to integrate Laravel Passport with social authentication providers

In this tutorial, we integrated Laravel Passport for API authentication with Laravel Socialite to implement social login in Laravel. This combination simplifies the login process while providing OAuth2-compliant, token-based authentication, which is important for securing modern web applications. With this setup, you can authenticate through social platforms, and your application can securely manage and protect access to API resources using tokens generated by Passport.

By leveraging Laravel Passport for API authentication and Laravel Socialite for social login, you can offer users a convenient way to sign in using their preferred platforms without compromising security. Happy coding!

Lucky Opuama is a software engineer and technical writer with a passion for exploring new tech stacks and writing about them. Connect with him on LinkedIn.