Install Socialite Keycloak (SSO) in Lumen 2022 (Work)

Post a Comment
Install Socialite Keycloak in Lumen

When I was working on a project using SSO (Single Sign On) Keycloak with the Lumen Back-End Framework, I had a hard time installing Socialite on Lumen.

After a day of experimenting, I finally found the solution so that Socialite can be used on Lumen.

This tutorial does not only apply to Keycloak providers, but also applies to other providers such as Facebook, Github, Gitlab, Twitch, Twitter and others.

If you are experiencing the same difficulty, then this tutorial will be very helpful for you.

Tutorial on installing Socialite on Lumen 2022 (Working):

1. Install Lumen Project

Install with this command:

composer create-project --prefer-dist laravel/lumen blog

For more detail installation you can visit the official website of Lumen at https://lumen.laravel.com/docs/9.x

2. Install Socialite Package

Install with this command:

composer require laravel/socialite

For more detail installation you can visit the official website of Laravel at https://laravel.com/docs/9.x/socialite#installation

3. Install Keycloack Platform

Install with this command:

composer require socialiteproviders/keycloak

For more detail installation you can visit the official website of Socialite at https://socialiteproviders.com/Keycloak/#installation-basic-usage

4. Create a config/services.php file

Copy services.php file from vendor/laravel/config/services.php into config/services.php

5. Modify config/services.php file

Paste this configuration into config/services.php file

'keycloak' => [
        'client_id' => env('KEYCLOAK_CLIENT_ID'),
        'client_secret' => env('KEYCLOAK_CLIENT_SECRET'),
        'redirect' => env('KEYCLOAK_REDIRECT_URI'),
        'base_url' => env('KEYCLOAK_BASE_URL'),   // Specify your keycloak server URL here
        'realms' => env('KEYCLOAK_REALM')         // Specify your keycloak realm
    ],

6. Configure app/Providers/EventServiceProvider

Configure the package's listener to listen for SocialiteWasCalled events.
Open EventServiceProvider.php file inside the provider directory, then paste this event inside the listener.

protected $listen = [
        \SocialiteProviders\Manager\SocialiteWasCalled::class => [
            \SocialiteProviders\Keycloak\KeycloakExtendSocialite::class.'@handle',
        ],
    ];


For more detail installation you can visit the official website of Socialite at https://socialiteproviders.com/Keycloak/#installation-basic-usage

7. Modify bootstrap/app.php

Register your KeycloakGuardServiceProvider under Create The Application:

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/

$app = new Laravel\Lumen\Application(
    dirname(__DIR__)
);

$app->register(Flipbox\LumenGenerator\LumenGeneratorServiceProvider::class);

$app->withFacades(); //Uncomment this line
$app->register(\KeycloakGuard\KeycloakGuardServiceProvider::class); //Copy and Paste this function

$app->withEloquent(); //Uncomment this line


Uncomment $app->withFacades(); and $app->withEloquent(); under "Create The Applicaation"

Under "Register Config Files" add: $app->configure('services');

/*
|--------------------------------------------------------------------------
| Register Config Files
|--------------------------------------------------------------------------
|
| Now we will register the "app" configuration file. If the file exists in
| your configuration directory it will be loaded; otherwise, we'll load
| the default version. You may register other files below as needed.
|
*/

$app->configure('app');
$app->configure('services'); //Copy and Paste this function

Uncomment auth middleware under Register Middleware:


/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
*/

// $app->middleware([
//     App\Http\Middleware\ExampleMiddleware::class
// ]);

$app->routeMiddleware([                                 //Uncomment this line
    'auth' => App\Http\Middleware\Authenticate::class,  //Uncomment this line
]);
                                                     //Uncomment this line

And then register your SocialiteServiceProvider in the ServiceProviders:

/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/

$app->register(App\Providers\AppServiceProvider::class);            //Uncomment this line
$app->register(App\Providers\AuthServiceProvider::class);           //Uncomment this line
$app->register(App\Providers\EventServiceProvider::class);          //Uncomment this line
$app->register(\SocialiteProviders\Manager\ServiceProvider::class); //Copy and Paste this function

8. Modify Providers/AuthServiceProvider

Paste this configuration inside the boot() function


/**
     * Boot the authentication services for the application.
     *
     * @return void
     */
    public function boot()
    {
        // Here you may define how you wish users to be authenticated for your Lumen
        // application. The callback which receives the incoming request instance
        // should return either a User instance or null. You're free to obtain
        // the User instance via an API token or any other method necessary.

        $this->app['auth']->viaRequest('api', function ($request) {
            try {
                $provider = Socialite::driver('keycloak');
                $data = $provider->stateless()->userFromToken($request->bearerToken())->user;
                return $data;
            } catch (\Throwable $throwable) {
                if ($throwable->getCode() != 401) {
                    report($throwable);
                }
            }
            return null;

        });
    }

9. Horrrayyyy... It's done for Socialite instalation in Lumen project, it should work now.

Now in my routes/web.php I can use Socialite like this:

$router->group(['middleware' => 'auth'], function () use ($router) {
    $router->get('/dashboard', function () use ($router) {
        dd(auth()->user());
    });
});

Keyword: Install Socialite Lumen, Lumen Socialite, Keycloak Lumen, Lumen Keycloak, Fix Socialite Lumen, Socialite Lumen Work

http://zsn-paper.blogspot.com

Related Posts

Post a Comment