Implement a custom driver for Laravel Socialite

Published on by

Implement a custom driver for Laravel Socialite image

Laravel Socialite is an official Laravel package to authenticate with OAuth providers. It supports authentication with Facebook, Twitter, LinkedIn, Google, GitHub, and Bitbucket. But, what if you want to use a different driver?

In our case we want to use AWS Cognito as an authentication provider. AWS Cognito allows you to authenticate using different providers, and stores centralized user data which you can use for different applications.

So, the first thing is to install Laravel Socialite, like this:

composer require laravel/socialite

Now, we create a CognitoProvider class which extends from \Socialite\Two\AbstractProvider. We need to implement the next methods, so the driver work as expected:

// ...
use Laravel\Socialite\Two\AbstractProvider;
 
class SocialiteCognitoProvider extends AbstractProvider
{
 
protected function getAuthUrl($state)
{
// TODO: Implement getAuthUrl() method.
}
 
protected function getTokenUrl()
{
// TODO: Implement getTokenUrl() method.
}
 
protected function getUserByToken($token)
{
// TODO: Implement getUserByToken() method.
}
 
protected function mapUserToObject(array $user)
{
// TODO: Implement mapUserToObject() method.
}
}

From the Laravel Socialite docs, we have to create a redirect route, which basically calls the redirect() method from the selected driver, like this:

use Laravel\Socialite\Facades\Socialite;
 
Route::get('/auth/redirect', function () {
return Socialite::driver('cognito')->redirect();
});

This redirect() method calls getAuthUrl() method under the hood where the user is redirected to the third-party provider authentication page. So, we need to provide this url in this method. We also extract how we get the base url in a different method, as we are going to use it in different places:

/**
* @return string
*/
public function getCognitoUrl()
{
return config('services.cognito.base_uri') . '/oauth2';
}
 
/**
* @param string $state
*
* @return string
*/
protected function getAuthUrl($state)
{
return $this->buildAuthUrlFromBase($this->getCognitoUrl() . '/authorize', $state);
}

The internal buildAuthUrlFromBase() method builds the authentication url with all the necessary parameters.

Once the user is authenticated on the third-party provider, they are redirected to the callback url that we define in our application. It depends on what you want to do on this controller method, but you will probably call the user() socialite method, like this:

Route::get('/auth/callback', function () {
$user = Socialite::driver('cognito')->user();
 
// $user->token
});

When you call this method, it calls the getTokenUrl() method to get the access token with the given code from the callback url params. So we need to provide this url:

/**
* @return string
*/
protected function getTokenUrl()
{
return $this->getCognitoUrl() . '/token';
}

Now that we have the access token we can get the authenticated user, which we'll do in the getUserByToken() method. In our case, we need to do a POST request like this:

/**
* @param string $token
*
* @throws GuzzleException
*
* @return array|mixed
*/
protected function getUserByToken($token)
{
$response = $this->getHttpClient()->post($this->getCognitoUrl() . '/userInfo', [
'headers' => [
'cache-control' => 'no-cache',
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/x-www-form-urlencoded',
],
]);
 
return json_decode($response->getBody()->getContents(), true);
}

Finally, we get a user object from the previous method, and we need to map this object into a new User class. In our case, we use Laravel\Socialite\Two\User, and map to the User with mapUserToObject(), like this:

/**
* @return User
*/
protected function mapUserToObject(array $user)
{
return (new User())->setRaw($user)->map([
'id' => $user['sub'],
'email' => $user['email'],
'username' => $user['username'],
'email_verified' => $user['email_verified'],
'family_name' => $user['family_name'],
]);
}

Now, in your callback() method, you could do something like this:

Route::get('/auth/callback', function () {
try {
$cognitoUser = Socialite::driver('cognito')->user();
$user = User::query()->whereEmail($cognitoUser->email)->first();
 
if (!$user) {
return redirect('login');
}
 
Auth::guard('web')->login($user);
 
return redirect(route('home'));
} catch (Exception $exception) {
return redirect('login');
}
});

Depending on the provider, you might need to add some scopes to the authentication request. The scopes are a mechanism to limit the access of an user to an application.

In AWS Cognito, there are system reserved scopes, these scopes are openid, email, phone, profile, and aws.cognito.signin.user.admin. To know more about these scopes, check here. You can also create custom scopes in Cognito, check here for more information.

In the SocialiteCognitoProvider class, you can define custom scopes by overriding the $scopes and $scopeSeparator internal variables like this:

class SocialiteCognitoProvider extends AbstractProvider
{
/**
* @var string[]
*/
protected $scopes = [
'openid',
'profile',
'aws.cognito.signin.user.admin',
];
 
/**
* @var string
*/
protected $scopeSeparator = ' ';
 
// ...
}

To know more about the AWS Cognito scopes, check the official docs here.

The final class will look like this:

// ...
 
use Laravel\Socialite\Two\User;
use GuzzleHttp\Exception\GuzzleException;
use Laravel\Socialite\Two\AbstractProvider;
 
class SocialiteCognitoProvider extends AbstractProvider
{
/**
* @var string[]
*/
protected $scopes = [
'openid',
'profile',
'aws.cognito.signin.user.admin',
];
 
/**
* @var string
*/
protected $scopeSeparator = ' ';
 
/**
* @return string
*/
public function getCognitoUrl()
{
return config('services.cognito.base_uri') . '/oauth2';
}
 
/**
* @param string $state
*
* @return string
*/
protected function getAuthUrl($state)
{
return $this->buildAuthUrlFromBase($this->getCognitoUrl() . '/authorize', $state);
}
 
/**
* @return string
*/
protected function getTokenUrl()
{
return $this->getCognitoUrl() . '/token';
}
 
/**
* @param string $token
*
* @throws GuzzleException
*
* @return array|mixed
*/
protected function getUserByToken($token)
{
$response = $this->getHttpClient()->post($this->getCognitoUrl() . '/userInfo', [
'headers' => [
'cache-control' => 'no-cache',
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/x-www-form-urlencoded',
],
]);
 
return json_decode($response->getBody()->getContents(), true);
}
 
/**
* @return User
*/
protected function mapUserToObject(array $user)
{
return (new User())->setRaw($user)->map([
'id' => $user['sub'],
'email' => $user['email'],
'username' => $user['username'],
'email_verified' => $user['email_verified'],
'family_name' => $user['family_name'],
]);
}
}

But, how does Socialite recognize the driver? We need to add some code in the AppServiceProvider:

// ...
use Laravel\Socialite\Contracts\Factory;
 
/**
* @throws BindingResolutionException
*/
public function boot()
{
$socialite = $this->app->make(Factory::class);
 
$socialite->extend('cognito', function () use ($socialite) {
$config = config('services.cognito');
 
return $socialite->buildProvider(SocialiteCognitoProvider::class, $config);
});
}

In the boot method, we register our driver in the Socialite manager, so when we call Socialite::driver('cognito') it instantiates our SocialiteCognitoProvider class.

And that’s it! This is how you implement a new custom driver for Laravel Socialite. To make your life easier, we created a small package for the custom Cognito driver, that you can check here.

Luis Güette photo

Luis, a software developer at Kirschbaum, has experience in Laravel, Vue.js, React, and Tailwind CSS. An AI and serverless apps enthusiast, he loves to build products from the ground up. Luis is always excited for the next challenge and enjoys learning new technologies.

Luis has a bachelor's degree in electrical engineering and has worked as an assistant professor in microcontrollers and digital systems. Prior to joining Kirschbaum Development he was a product specialist for a software development company, focused on IoT products.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Laravel Idea for PhpStorm logo

Laravel Idea for PhpStorm

Ultimate PhpStorm plugin for Laravel developers, delivering lightning-fast code completion, intelligent navigation, and powerful generation tools to supercharge productivity.

Laravel Idea for PhpStorm
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
JetShip - Laravel Starter Kit logo

JetShip - Laravel Starter Kit

A Laravel SaaS Boilerplate and a starter kit built on the TALL stack. It includes authentication, payments, admin panels, and more. Launch scalable apps fast with clean code, seamless deployment, and custom branding.

JetShip - Laravel Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Streamlining Route Parameters in Laravel Using URL Defaults image

Streamlining Route Parameters in Laravel Using URL Defaults

Read article
Flexible Docker Images with PHP INI Environment Variables image

Flexible Docker Images with PHP INI Environment Variables

Read article
Dynamic Form Validation in Laravel with prohibited_if image

Dynamic Form Validation in Laravel with prohibited_if

Read article
Add Approvals to Your Laravel Application image

Add Approvals to Your Laravel Application

Read article
Enhancing Data Processing with Laravel's transform() Method image

Enhancing Data Processing with Laravel's transform() Method

Read article
Get Xdebug Working With Docker and PHP 8.4 in One Minute image

Get Xdebug Working With Docker and PHP 8.4 in One Minute

Read article