Access Management

Laravel SSO with Socialite: Social Login for Your Laravel Apps

What is Laravel? 

Laravel is an open-source PHP framework that is used to build web applications following the model-view-controller (MVC) architectural pattern. Its expressive, elegant syntax aims to make web development tasks, such as routing, caching, and security, easier and more effective.

Laravel was created by Taylor Otwell and was first released in 2011. Over the years, it has grown in popularity and is now considered one of the most popular web development frameworks. Laravel is lauded for its ability to handle complex web applications securely and at a higher speed than other frameworks. It also provides tools and resources to build everything from small projects to enterprise-level applications.

Laravel has an extensive ecosystem, including a wide array of tools and libraries that cater to the different needs of modern web development. Among these tools is Laravel Socialite, which I will delve into later in the article.

This is part of a series of articles about SSO

In this article:

Importance of SSO in Laravel Applications 

Single Sign-On (SSO) is an authentication process that allows a user to access multiple applications or websites by logging in just once, with one set of credentials. There are several advantages to using SSO in your Laravel applications:

  • Improved security: Security is a critical concern in web development. With Laravel SSO, you minimize the risk of password fatigue, where users, overwhelmed by the need to remember multiple passwords, resort to using weak or repeated passwords. By reducing the number of login credentials, you also reduce the risk of phishing attacks.
  • Improve user experience: SSO provides an enhanced user experience by eliminating the need for users to remember multiple credentials. With SSO, users need to authenticate just once to gain access to multiple applications or websites, providing a seamless user experience.
  • Streamlining authentication processes: SSO streamlines the authentication process in application development. With SSO, the authentication process is handled by an external provider, making development easier and reducing the chances of bugs and errors in your authentication mechanisms.
  • Reduced administrative overhead: With SSO, administrators no longer need to manage multiple user databases and credentials. In addition, it eliminates the need to manage password resets and user authentication issues, significantly reducing the burden on network administration staff.

Related content: Read our guide to Single Sign On solutions

What is Laravel Socialite? 

Laravel Socialite is an optional, Laravel 5.x+ compatible package that provides a simple, convenient way to authenticate with OAuth providers. Socialite currently supports authentication with Facebook, Twitter, LinkedIn, Google, GitHub, and Bitbucket.

Laravel Socialite makes it easy to implement SSO in your Laravel applications. With Socialite, you can quickly and easily authenticate users via social login, providing a seamless experience for users already using those social platforms. Furthermore, Socialite’s expressive API makes the process of implementing SSO a breeze, even for developers who do not have extensive experience with authentication.

Tutorial: Implementing OAuth2 Single Sign-On (SSO) with Laravel Socialite 

Register Your Laravel Application with the Identity Provider

The first step in our Laravel SSO journey is registering the Laravel application with an identity provider (IdP). The IdP is a system that authenticates users and sends their data to a service provider (SP), which in our case is the Laravel application. Common examples of IdPs include Google, Facebook, and Twitter.

To register your Laravel application, visit the IdP’s developer portal. For instance, if you’re using Google as your IdP, visit the Google API Console. Create a new project, and under the Credentials section, create an OAuth client ID. You will be prompted to enter some information about your application, such as the authorized JavaScript origins and the authorized redirect URIs. Make sure you enter the correct details as this will facilitate seamless communication between your Laravel application and the IdP.

Once you’ve successfully created the OAuth client ID, the IdP will provide a client ID and a client secret. These are vital credentials as they allow your application to identify itself to the IdP. Ensure you save these credentials securely as you will need them in the subsequent stages of configuring Laravel SSO.

Note: You will need a live domain and valid SSL to create an OAuth client using Google.

Install Laravel Socialite

Laravel Socialite is a package provided by Laravel to simplify the OAuth authentication process. Before installing Socialite, ensure your Laravel application is up to date. You can check your Laravel version by running the command php artisan –version in your terminal.

To install Socialite, you need to use Composer, a tool for dependency management in PHP. Run the command composer require laravel/socialite in your terminal. This command instructs Composer to download the Socialite package and install it in your Laravel application.

Once the installation process is complete, open your config/app.php file and add the Socialite service provider to the providers array: 

Laravel\Socialite\SocialiteServiceProvider::class,

Next, add the Socialite facade to the aliases array: 

'Socialite' => Laravel\Socialite\Facades\Socialite::class,

With this, you have successfully installed Laravel Socialite in your application.

Configure Socialite

Now that we have installed Socialite, it’s time to configure it to work with our Laravel application. First, open the config/services.php file. This file is where we define all the services that our Laravel application will interact with.In the services.php file, add an array that corresponds to the IdP you’re using.

For instance, if you’re using Google, your array should look like this:

Remember the client ID and client secret that you received when you registered your application with the IdP? This is where they come into play. The env() function retrieves the values from the .env file, which we will update in the next section.

Update .env File

The .env file is a crucial component in a Laravel application as it stores configuration variables. These variables can be accessed throughout the application, making the .env file an ideal place to store sensitive information such as database credentials and API keys.

Open your .env file and add the following lines:

Replace your-google-client-id and your-google-client-secret with the actual client ID and client secret that you received from the IdP. Replace http://your-app-url/callback with your application’s callback URL. This URL is where the IdP will redirect the user after they have authenticated.

Create OAuth Routes

Routes in Laravel define the URLs that your application responds to. For our Laravel SSO implementation, we need to create two routes: one for redirecting the user to the IdP, and another one for handling the callback from the IdP.

Open your routes/web.php file and add the following lines:

The redirectToProvider method will redirect the user to the IdP, while the handleProviderCallback method will handle the callback from the IdP.

Create Controller Methods

With our routes in place, it’s now time to create the controller methods that will handle the OAuth flow. Laravel provides a command-line tool called Artisan that we can use to generate a new controller. Run the command php artisan make:controller OAuthController in your terminal to create a new controller.

Open your OAuthController.php file and add the following lines:

The redirectToProvider method redirects the user to the IdP. The handleProviderCallback method receives the callback from the IdP, retrieves the user’s information, and then you can implement your logic, like creating a user session or storing the user’s information in your database.

Implement OAuth2 Flow in Controller

Now that we have our controller methods in place, let’s see how to implement an OAuth2 flow. This is a series of steps that the IdP and the SP go through to authenticate the user.

In your handleProviderCallback method, after retrieving the user’s information, you should check if the user already exists in your database. If the user exists, you should log them in; otherwise, you should create a new user and then log them in.

Here’s a sample implementation:

In this code, the findOrCreateUser method checks if the user exists in the database. If the user exists, it returns the user; otherwise, it creates a new user and then returns the new user.

Test the SSO Flow

With all the pieces in place, it’s now time to test our Laravel SSO implementation. Open your web browser and visit the URL that corresponds to the redirectToProvider route. If you’ve done everything correctly, you should be redirected to the IdP’s login page.

Log in with your credentials. After successful authentication, you should be redirected back to your Laravel application. If you check your database, you should see a new user record corresponding to the authenticated user.

Laravel SSO with Frontegg 

Frontegg is a user management solution with full support for Laravel. Once you integrate Frontegg’s self-served user management solution, your customers can configure their SSO completely on their own with just a few lines of code. The single sign-on can be integrated with IDPs with commonly-used protocols like OIDC and SAML. Yes, you can implement social login SSOs as well. The front end has been taken care of as well. 

You can leverage all of Frontegg’s SSO components and personalize your SaaS offering with a login box builder. This embeddable box reduces implementation times as no in-house development is required. Users can authenticate smoothly and gain quick access to the app, without waiting for product updates and fixes. A true end-to-end SSO solution for SaaS apps and services.

Learn more about Frontegg for authentication

Looking to take your User Management to the next level?

Sign up. It's free