RealmDeployDocs
GuidesFramework quickstarts

Add Keycloak login to a Laravel app

Sign users in to a Laravel 13 app with Keycloak through Socialite and the SocialiteProviders driver, protect API routes with firebase/php-jwt, and log out.

A Laravel app signs users in with the authorization code flow and PKCE through Laravel Socialite and the socialiteproviders/keycloak driver, keeps them in Laravel's normal session, and checks Keycloak access tokens on its API routes with a small middleware built on firebase/php-jwt.

Written against Laravel 13.44, PHP 8.5, laravel/socialite 5.33, socialiteproviders/keycloak 5.3.0 (with socialiteproviders/manager 4.10), firebase/php-jwt 7.2 and Keycloak 26.8, checked on 25 November 2026.

Replace auth.example.com with your RealmDeploy hostname and acme with your realm.

Create the client in Keycloak

Open Clients, choose Create client, and use these values:

SettingValue
Client typeOpenID Connect
Client IDlaravel-app
Client authenticationOn
Authentication flowStandard flow. Turn Direct access grants off.
Root URLhttp://localhost:8000
Valid redirect URIshttp://localhost:8000/auth/callback
Valid post logout redirect URIshttp://localhost:8000
Web originsLeave empty. The browser never calls Keycloak from JavaScript.

Choose Save, then copy the secret from the Credentials tab.

For production, add your app's real URLs next to the local ones, for example https://app.example.com/auth/callback and https://app.example.com. Keycloak compares redirect URIs exactly.

Environment variables

The driver takes the Keycloak server and the realm separately, not the issuer URL. The names are the ones the driver's README uses, plus one for the API's audience:

.env
APP_URL=http://localhost:8000

KEYCLOAK_BASE_URL=https://auth.example.com
KEYCLOAK_REALM=acme
KEYCLOAK_CLIENT_ID=laravel-app
KEYCLOAK_CLIENT_SECRET=paste-the-client-secret
KEYCLOAK_REDIRECT_URI=http://localhost:8000/auth/callback
KEYCLOAK_API_AUDIENCE=orders-api

Install

composer require socialiteproviders/keycloak firebase/php-jwt

This also installs laravel/socialite and socialiteproviders/manager.

Add login

Add the driver's settings to config/services.php. The realms key is the driver's own name for the realm:

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'),
    'realms' => env('KEYCLOAK_REALM'),
    'audience' => env('KEYCLOAK_API_AUDIENCE'),
],

Laravel 11 and later have no EventServiceProvider, so register the driver in AppServiceProvider, as the driver's README says for Laravel 11+:

app/Providers/AppServiceProvider.php
<?php

namespace App\Providers;

use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
use SocialiteProviders\Keycloak\Provider as KeycloakProvider;
use SocialiteProviders\Manager\SocialiteWasCalled;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        //
    }

    public function boot(): void
    {
        Event::listen(function (SocialiteWasCalled $event) {
            $event->extendSocialite('keycloak', KeycloakProvider::class);
        });
    }
}

Users are stored in Laravel's users table, matched by their Keycloak user ID. Add a column for it, and let password be empty because Keycloak checks passwords:

database/migrations/2026_11_25_000000_add_keycloak_id_to_users_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('keycloak_id')->nullable()->unique();
            $table->string('password')->nullable()->change();
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropUnique(['keycloak_id']);
            $table->dropColumn('keycloak_id');
        });
    }
};

In app/Models/User.php, add keycloak_id to the fillable attributes: #[Fillable(['name', 'email', 'password', 'keycloak_id'])]. Then run php artisan migrate.

routes/web.php
<?php

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Laravel\Socialite\Socialite;

Route::get('/', function () {
    return Auth::check()
        ? 'Signed in as '.e(Auth::user()->name).
          '<form method="post" action="/logout">'.csrf_field().'<button>Sign out</button></form>'
        : '<a href="/auth/redirect">Sign in</a>';
});

Route::get('/auth/redirect', function () {
    return Socialite::driver('keycloak')->enablePKCE()->redirect();
})->name('login');

Route::get('/auth/callback', function (Request $request) {
    $keycloakUser = Socialite::driver('keycloak')->enablePKCE()->user();

    $user = User::updateOrCreate(
        ['keycloak_id' => $keycloakUser->getId()],
        ['name' => $keycloakUser->getName() ?? $keycloakUser->getNickname(), 'email' => $keycloakUser->getEmail()],
    );

    Auth::login($user);
    $request->session()->regenerate();
    // Keep the ID token: Keycloak's logout endpoint uses it as id_token_hint.
    $request->session()->put('keycloak_id_token', $keycloakUser->accessTokenResponseBody['id_token'] ?? null);

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

Route::post('/logout', function (Request $request) {
    $idToken = $request->session()->get('keycloak_id_token');

    Auth::logout();
    $request->session()->invalidate();
    $request->session()->regenerateToken();

    return redirect(Socialite::driver('keycloak')->getLogoutUrl(
        url('/'),
        config('services.keycloak.client_id'),
        $idToken,
    ));
})->middleware('auth');

enablePKCE() must be called on both routes: the first stores the PKCE verifier in the session, the second sends it with the code. Socialite checks state, exchanges the code with the client secret at /protocol/openid-connect/token, and reads the user from the realm's /protocol/openid-connect/userinfo endpoint with the access token. It does not validate the ID token itself, which is fine here because the app only keeps it to pass back to Keycloak at logout. The route named login is where Laravel's auth middleware sends visitors who are not signed in.

Start the app on localhost, so the browser keeps one session cookie for the whole login:

php artisan serve --host=localhost

Open http://localhost:8000 and choose Sign in.

Protect an API

Routes under /api accept Authorization: Bearer <access token> from other clients and check the token's signature, issuer and audience.

Keycloak does not put your API in the access token's aud claim by default, so add an Audience mapper to the client whose tokens call the API:

  1. Open Clients, choose that client, and open its Client scopes tab.
  2. Choose <client-id>-dedicated.
  3. Choose Configure a new mapper (or Add mapper → By configuration), then Audience.
  4. Enter a Name, set Included Custom Audience to orders-api, keep Add to access token on, and choose Save.

If your API is registered as a client in the realm, pick it under Included Client Audience instead and use its client ID as KEYCLOAK_API_AUDIENCE.

firebase/php-jwt checks the signature and the exp, nbf and iat claims; the middleware checks iss and aud itself. It fetches the realm's keys from /protocol/openid-connect/certs, caches them for an hour in Laravel's cache, and fetches them again, at most once a minute, when a token arrives with a key ID it does not know:

app/Http/Middleware/VerifyKeycloakToken.php
<?php

namespace App\Http\Middleware;

use Closure;
use Firebase\JWT\JWK;
use Firebase\JWT\JWT;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Symfony\Component\HttpFoundation\Response;
use Throwable;

class VerifyKeycloakToken
{
    public function handle(Request $request, Closure $next, ?string $role = null): Response
    {
        $token = $request->bearerToken();
        $issuer = rtrim(config('services.keycloak.base_url'), '/').'/realms/'.config('services.keycloak.realms');

        try {
            // Checks the signature against the realm's keys, plus exp, nbf and iat.
            $claims = JWT::decode((string) $token, $this->keys($issuer, (string) $token));
        } catch (Throwable) {
            return response()->json(['error' => 'invalid_token'], 401);
        }

        $audiences = (array) ($claims->aud ?? []);
        if (($claims->iss ?? null) !== $issuer
            || ! in_array(config('services.keycloak.audience'), $audiences, true)) {
            return response()->json(['error' => 'invalid_token'], 401);
        }

        if ($role !== null && ! in_array($role, $claims->realm_access->roles ?? [], true)) {
            return response()->json(['error' => 'insufficient_scope'], 403);
        }

        $request->attributes->set('token_claims', $claims);

        return $next($request);
    }

    private function keys(string $issuer, string $token): array
    {
        $header = JWT::jsonDecode(JWT::urlsafeB64Decode(explode('.', $token)[0]));
        $keys = JWK::parseKeySet($this->jwks($issuer), 'RS256');

        // Unknown key ID: Keycloak may have rotated its keys. Refetch, at most once a minute.
        if (! isset($keys[$header->kid ?? '']) && Cache::add('keycloak:jwks:refreshed', true, 60)) {
            Cache::forget('keycloak:jwks');
            $keys = JWK::parseKeySet($this->jwks($issuer), 'RS256');
        }

        return $keys;
    }

    private function jwks(string $issuer): array
    {
        return Cache::remember('keycloak:jwks', 3600, fn () => Http::timeout(5)
            ->get($issuer.'/protocol/openid-connect/certs')
            ->throw()
            ->json());
    }
}

Each key in the set keeps its own algorithm, and JWT::decode refuses a token whose alg header does not match the key it names, so a token cannot switch to another algorithm. The optional middleware parameter is a realm role from Keycloak's realm_access.roles claim.

A fresh Laravel 13 app has no routes/api.php. Create it, and load it in bootstrap/app.php by adding api: __DIR__.'/../routes/api.php', to withRouting(...). Laravel puts these routes under /api without sessions or CSRF checks:

routes/api.php
<?php

use App\Http\Middleware\VerifyKeycloakToken;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware(VerifyKeycloakToken::class)->group(function () {
    Route::get('/me', function (Request $request) {
        $claims = $request->attributes->get('token_claims');

        return ['subject' => $claims->sub, 'username' => $claims->preferred_username ?? null];
    });
});

Route::get('/admin/ping', fn () => ['status' => 'ok'])
    ->middleware(VerifyKeycloakToken::class.':admin');

A token without the orders-api audience, from another issuer, or with a bad signature gets a 401; a valid token without the admin realm role gets a 403 on /api/admin/ping. Paste a token into the JWT decoder to see its iss, aud and realm_access, or check its key ID against the realm's keys with the JWT kid matcher.

Log out

The sign-out form posts to /logout. The route ends the Laravel session, then sends the browser to the URL the driver's getLogoutUrl() builds: the realm's end-session endpoint, https://auth.example.com/realms/acme/protocol/openid-connect/logout, with post_logout_redirect_uri, client_id and id_token_hint. url('/') is http://localhost:8000, which must be listed in Valid post logout redirect URIs. Because the ID token is sent, Keycloak ends its own session without asking. The logout URL builder shows the same URL.

The route is a POST with Laravel's CSRF token, so another site cannot log your users out with a link or an image tag.

This logout runs through the browser, so it needs nothing from us. If you also set a Backchannel logout URL on the client, Keycloak calls your app from your tenant, and outgoing connections from your tenant are closed by default. Tell us the host and port first through How to reach us and we open the connection.

Common errors

ErrorCauseFix
Driver [keycloak] not supported.The SocialiteWasCalled listener is not registered.Add the Event::listen call to AppServiceProvider::boot.
Keycloak shows Invalid parameter: redirect_uriKEYCLOAK_REDIRECT_URI is not in Valid redirect URIs, or differs in scheme, host or port.Add it exactly. Compare both with the redirect URI matcher.
Laravel\Socialite\Two\InvalidStateException on the callbackThe session cookie from /auth/redirect did not come back, for example because you opened 127.0.0.1:8000 and the callback goes to localhost:8000.Use one hostname throughout, the one in KEYCLOAK_REDIRECT_URI.
ClientException with 401 Unauthorized and unauthorized_client on the callbackThe client secret is wrong, or Client authentication is off.Copy the secret again from the Credentials tab.
Keycloak answers Sign in with a page-not-found errorKEYCLOAK_BASE_URL contains /realms/acme, or KEYCLOAK_REALM is wrong, so the driver builds a URL for a realm that does not exist.Set the base URL to https://auth.example.com only. Check the realm's URLs with the realm endpoints tool.
Keycloak shows Invalid redirect uri after Sign outhttp://localhost:8000 is not in Valid post logout redirect URIs.Add it exactly, without a trailing slash.
API returns 401 for a token that decodes fineThe token has no orders-api audience, or iss differs from KEYCLOAK_BASE_URL plus /realms/ plus KEYCLOAK_REALM.Add the Audience mapper above and get a new token. Check it with the JWT claims validator.

For other OAuth error codes, see the OAuth error lookup.

FAQ

Why not validate tokens with a Keycloak package for Laravel?

You can, but the middleware above is all it takes, with one maintained library. firebase/php-jwt also offers CachedKeySet, which fetches and caches the key set for you; it needs a PSR-6 cache and a PSR-18 HTTP client, which a fresh Laravel app does not include, so we use JWK::parseKeySet with Laravel's own cache instead.

Can a single-page app call the API with its own tokens?

Yes. Give the single-page app its own public client (Client authentication off) with PKCE, add the Audience mapper to that client, and send its access token in the Authorization header. The API does not care which client a token was issued to, only that its issuer and audience match.

What changes behind a reverse proxy?

When a proxy ends TLS, Laravel sees http:// and url('/') builds an http:// address. Trust the proxy in bootstrap/app.php with $middleware->trustProxies(at: '*') inside withMiddleware(...), or list the proxy's addresses instead of *.

Where do roles for the web session come from?

Socialite reads the user from the userinfo endpoint, which does not include realm roles by default. If the web app needs them, keep $keycloakUser->token (the access token) in the session and read realm_access.roles from it with the same JWT::decode call the middleware uses.

Sources

On this page