Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Lars_M's avatar
Level 4

Laravel Jetstream & Keycloak

Hey community!

I think I have a mental block or simply too little experience.

I would like to convert my existing Laravel Jetstream application to Keycloak.

Has anyone done this before? My application provides APIs. However, I haven't quite figured out how Keycloak can provide bearer tokens?

I did some tests with “vizir/laravel-keycloak-web-guard”, unfortunately the package does not work with Laravel 10^ and Jetstream.

Best regards Lars

0 likes
1 reply
LaryAI's avatar
Level 58

To integrate Keycloak with a Laravel Jetstream application, you can follow these steps. This solution assumes you have a basic understanding of Laravel, Jetstream, and OAuth2 concepts.

Step 1: Install Required Packages

First, you need to install the socialite package to handle OAuth2 authentication.

composer require laravel/socialite

Step 2: Configure Keycloak

  1. Create a new client in Keycloak:

    • Go to your Keycloak admin console.
    • Create a new client and set the Access Type to confidential.
    • Set the Valid Redirect URIs to your Laravel application's callback URL, e.g., http://your-app-url/auth/callback.
  2. Get the client credentials:

    • Note down the Client ID and Client Secret.

Step 3: Configure Laravel

  1. Add Keycloak configuration to config/services.php:
'keycloak' => [
    'client_id' => env('KEYCLOAK_CLIENT_ID'),
    'client_secret' => env('KEYCLOAK_CLIENT_SECRET'),
    'redirect' => env('KEYCLOAK_REDIRECT_URI'),
    'base_url' => env('KEYCLOAK_BASE_URL'),
    'realm' => env('KEYCLOAK_REALM'),
],
  1. Add environment variables to .env:
KEYCLOAK_CLIENT_ID=your-client-id
KEYCLOAK_CLIENT_SECRET=your-client-secret
KEYCLOAK_REDIRECT_URI=http://your-app-url/auth/callback
KEYCLOAK_BASE_URL=http://your-keycloak-url
KEYCLOAK_REALM=your-realm

Step 4: Create a Custom Socialite Provider

Create a custom provider for Keycloak by extending the Socialite provider.

  1. Create a new service provider:
php artisan make:provider KeycloakServiceProvider
  1. Register the custom provider in KeycloakServiceProvider:
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Laravel\Socialite\Contracts\Factory as Socialite;

class KeycloakServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(Socialite::class, function ($app) {
            $config = $app['config']['services.keycloak'];
            return new \Laravel\Socialite\Two\KeycloakProvider(
                $app['request'], $config['client_id'], $config['client_secret'], $config['redirect']
            );
        });
    }

    public function boot()
    {
        //
    }
}
  1. Register the service provider in config/app.php:
'providers' => [
    // Other Service Providers
    App\Providers\KeycloakServiceProvider::class,
],

Step 5: Create Authentication Routes and Controller

  1. Add routes in routes/web.php:
use App\Http\Controllers\Auth\LoginController;

Route::get('auth/redirect', [LoginController::class, 'redirectToProvider']);
Route::get('auth/callback', [LoginController::class, 'handleProviderCallback']);
  1. Create the LoginController:
namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

class LoginController extends Controller
{
    public function redirectToProvider()
    {
        return Socialite::driver('keycloak')->redirect();
    }

    public function handleProviderCallback()
    {
        $user = Socialite::driver('keycloak')->user();

        // Find or create the user in your database
        $authUser = User::firstOrCreate([
            'email' => $user->email,
        ], [
            'name' => $user->name,
            'password' => bcrypt(Str::random(24)),
        ]);

        Auth::login($authUser, true);

        return redirect()->intended('/home');
    }
}

Step 6: Handle Bearer Tokens

To handle bearer tokens for your API, you can use Laravel Passport or Sanctum. Here is a basic example using Passport:

  1. Install Passport:
composer require laravel/passport
  1. Run the Passport installation command:
php artisan passport:install
  1. Configure Passport in AuthServiceProvider:
use Laravel\Passport\Passport;

public function boot()
{
    $this->registerPolicies();

    Passport::routes();
}
  1. Add the HasApiTokens trait to your User model:
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}
  1. Configure API authentication in config/auth.php:
'guards' => [
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

Conclusion

This setup should help you integrate Keycloak with your Laravel Jetstream application. You can now authenticate users via Keycloak and handle bearer tokens for your API. If you encounter any issues, make sure to check the Keycloak and Laravel logs for more details.

Please or to participate in this conversation.