Implement a custom driver for Laravel Socialite

Tutorials

March 11th, 2022

Kirschbaumsocialite.jpg

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:

1composer 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:

1// ...
2use Laravel\Socialite\Two\AbstractProvider;
3 
4class SocialiteCognitoProvider extends AbstractProvider
5{
6 
7 protected function getAuthUrl($state)
8 {
9 // TODO: Implement getAuthUrl() method.
10 }
11 
12 protected function getTokenUrl()
13 {
14 // TODO: Implement getTokenUrl() method.
15 }
16 
17 protected function getUserByToken($token)
18 {
19 // TODO: Implement getUserByToken() method.
20 }
21 
22 protected function mapUserToObject(array $user)
23 {
24 // TODO: Implement mapUserToObject() method.
25 }
26}

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

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

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:

1/**
2 * @return string
3 */
4public function getCognitoUrl()
5{
6 return config('services.cognito.base_uri') . '/oauth2';
7}
8 
9/**
10 * @param string $state
11 *
12 * @return string
13 */
14protected function getAuthUrl($state)
15{
16 return $this->buildAuthUrlFromBase($this->getCognitoUrl() . '/authorize', $state);
17}

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:

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

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:

1/**
2 * @return string
3 */
4protected function getTokenUrl()
5{
6 return $this->getCognitoUrl() . '/token';
7}

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:

1/**
2 * @param string $token
3 *
4 * @throws GuzzleException
5 *
6 * @return array|mixed
7 */
8protected function getUserByToken($token)
9{
10 $response = $this->getHttpClient()->post($this->getCognitoUrl() . '/userInfo', [
11 'headers' => [
12 'cache-control' => 'no-cache',
13 'Authorization' => 'Bearer ' . $token,
14 'Content-Type' => 'application/x-www-form-urlencoded',
15 ],
16 ]);
17 
18 return json_decode($response->getBody()->getContents(), true);
19}

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:

1/**
2 * @return User
3 */
4protected function mapUserToObject(array $user)
5{
6 return (new User())->setRaw($user)->map([
7 'id' => $user['sub'],
8 'email' => $user['email'],
9 'username' => $user['username'],
10 'email_verified' => $user['email_verified'],
11 'family_name' => $user['family_name'],
12 ]);
13}

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

1Route::get('/auth/callback', function () {
2 try {
3 $cognitoUser = Socialite::driver('cognito')->user();
4 $user = User::query()->whereEmail($cognitoUser->email)->first();
5 
6 if (!$user) {
7 return redirect('login');
8 }
9 
10 Auth::guard('web')->login($user);
11 
12 return redirect(route('home'));
13 } catch (Exception $exception) {
14 return redirect('login');
15 }
16});

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:

1class SocialiteCognitoProvider extends AbstractProvider
2{
3 /**
4 * @var string[]
5 */
6 protected $scopes = [
7 'openid',
8 'profile',
9 'aws.cognito.signin.user.admin',
10 ];
11 
12 /**
13 * @var string
14 */
15 protected $scopeSeparator = ' ';
16 
17 // ...
18}

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

The final class will look like this:

1// ...
2 
3use Laravel\Socialite\Two\User;
4use GuzzleHttp\Exception\GuzzleException;
5use Laravel\Socialite\Two\AbstractProvider;
6 
7class SocialiteCognitoProvider extends AbstractProvider
8{
9 /**
10 * @var string[]
11 */
12 protected $scopes = [
13 'openid',
14 'profile',
15 'aws.cognito.signin.user.admin',
16 ];
17 
18 /**
19 * @var string
20 */
21 protected $scopeSeparator = ' ';
22 
23 /**
24 * @return string
25 */
26 public function getCognitoUrl()
27 {
28 return config('services.cognito.base_uri') . '/oauth2';
29 }
30 
31 /**
32 * @param string $state
33 *
34 * @return string
35 */
36 protected function getAuthUrl($state)
37 {
38 return $this->buildAuthUrlFromBase($this->getCognitoUrl() . '/authorize', $state);
39 }
40 
41 /**
42 * @return string
43 */
44 protected function getTokenUrl()
45 {
46 return $this->getCognitoUrl() . '/token';
47 }
48 
49 /**
50 * @param string $token
51 *
52 * @throws GuzzleException
53 *
54 * @return array|mixed
55 */
56 protected function getUserByToken($token)
57 {
58 $response = $this->getHttpClient()->post($this->getCognitoUrl() . '/userInfo', [
59 'headers' => [
60 'cache-control' => 'no-cache',
61 'Authorization' => 'Bearer ' . $token,
62 'Content-Type' => 'application/x-www-form-urlencoded',
63 ],
64 ]);
65 
66 return json_decode($response->getBody()->getContents(), true);
67 }
68 
69 /**
70 * @return User
71 */
72 protected function mapUserToObject(array $user)
73 {
74 return (new User())->setRaw($user)->map([
75 'id' => $user['sub'],
76 'email' => $user['email'],
77 'username' => $user['username'],
78 'email_verified' => $user['email_verified'],
79 'family_name' => $user['family_name'],
80 ]);
81 }
82}

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

1// ...
2use Laravel\Socialite\Contracts\Factory;
3 
4/**
5 * @throws BindingResolutionException
6 */
7public function boot()
8{
9 $socialite = $this->app->make(Factory::class);
10 
11 $socialite->extend('cognito', function () use ($socialite) {
12 $config = config('services.cognito');
13 
14 return $socialite->buildProvider(SocialiteCognitoProvider::class, $config);
15 });
16}

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.

Filed in:

Luis Güette

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.

Laravel News Partners