Need help with laravel-keycloak-guard?
Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

About the developer

149 Stars 53 Forks 37 Commits 1 Opened issues


🔑 Simple Keycloak Guard for Laravel / Lumen

Services available


Need anything else?

Contributors list


Simple Keycloak Guard for Laravel / Lumen

This package helps you authenticate users on a Laravel API based on JWT tokens generated from Keycloak Server.


✔️ I`m building an API with Laravel.

✔️ I will not use Laravel Passport for authentication, because Keycloak Server will do the job.

✔️ The frontend is a separated project.

✔️ The frontend users authenticate directly on Keycloak Server to obtain a JWT token. This process have nothing to do with the Laravel API.

✔️ The frontend keep the JWT token from Keycloak Server.

✔️ The frontend make requests to the Laravel API, with that token.

💔 If your app does not match requirements, probably you are looking for

The flow

  1. The frontend user authenticates on Keycloak Server

  2. The frontend user obtains a JWT token.

  3. In another moment, the frontend user makes a request to some protected endpoint on a Laravel API, with that token.

  4. The Laravel API (through

    Keycloak Guard
    ) handle it.
    • Verify token signature.
    • Verify token structure.
    • Verify token expiration time.
    • Verify if my API allows
      resource access
      from token.
  5. If everything is ok, find the user on database and authenticate it on my API.

  6. Return response


Laravel / Lumen

Require the package

composer require robsontenorio/laravel-keycloak-guard

Lumen only

Register the provider in your boostrap app file


Add the following line in the "Register Service Providers" section at the bottom of the file.


For facades, uncomment

in your boostrap app file


Keycloak Guard

The Keycloak Guard configuration can be handled from Laravel

file. ⚠️ Be sure all strings are trimmed.

Optionally you can publish the config file.

php artisan vendor:publish  --provider="KeycloakGuard\KeycloakGuardServiceProvider"

'load_user_from_database' => env('KEYCLOAK_LOAD_USER_FROM_DATABASE', true),

'user_provider_credential' => env('KEYCLOAK_USER_PROVIDER_CREDENTIAL', 'username'),

'token_principal_attribute' => env('KEYCLOAK_TOKEN_PRINCIPAL_ATTRIBUTE', 'preferred_username'),

'append_decoded_token' => env('KEYCLOAK_APPEND_DECODED_TOKEN', false),

'allowed_resources' => env('KEYCLOAK_ALLOWED_RESOURCES', null) ];

✔️ realmpublickey


The Keycloak Server realm public key (string).

How to get realm public key? Click on "Realm Settings" > "Keys" > "Algorithm RS256" Line > "Public Key" Button

✔️ loaduserfrom_database

Required. Default is


If you do not have an

table you must disable this.

It fetchs user from database and fill values into authenticated user object. If enabled, it will work together with


✔️ userprovidercredential

Required. Default is


The field from "users" table that contains the user unique identifier (eg. username, email, nickname). This will be confronted against

attribute, while authenticating.

✔️ tokenprincipalattribute

Required. Default is


The property from JWT token that contains the user identifier. This will be confronted against

attribute, while authenticating.

✔️ appenddecodedtoken

Default is


Appends to the authenticated user the full decoded JWT token (

). Useful if you need to know roles, groups and other user info holded by JWT token. Even choosing
, you can also get it using
, see API section.

✔️ allowed_resources


Usually you API should handle one resource_access. But, if you handle multiples, just use a comma separated list of allowed resources accepted by API. This attribute will be confronted against

attribute from JWT token, while authenticating.

Laravel Auth

Changes on

'defaults' => [
        'guard' => 'api', # m building an API
        'passwords' => 'users',

'guards' => [ 'api' => [ 'driver' => 'keycloak', # 'users', ], ],

Laravel Routes

Just protect some endpoints on routes/api.php and you are done!

```php // public endpoints Route::get('/hello', function () { return ':)'; });

// protected endpoints Route::group(['middleware' => 'auth:api'], function () { Route::get('/protected-endpoint', '[email protected]'); // more endpoints ... });

Lumen Routes

Just protect some endpoints on

and you are done!
// public endpoints
$router->get('/hello', function () {
    return ':)';

// protected endpoints $router->group(['middleware' => 'auth'], function () { $router->get('/protected-endpoint', '[email protected]'); // more endpoints ... });


Simple Keycloak Guard implements

. So, all Laravel default methods will be available. Ex:
returns the authenticated user.

Default methods:

  • check()
  • guest()
  • user()
  • id()
  • validate()
  • setUser()

Keycloak Guard methods:

  • token()


returns full decoded JWT token from authenticated user
  • hasRole('some-resource', 'some-role'): Check if the authenticated user has especific role into a resource.

Ex: Whit this payload:

'resource_access' => [
  'myapp-backend' => [
      'roles' => [
  'myapp-frontend' => [
    'roles' => [
Auth::hasRole('myapp-backend', 'myapp-backend-role1') // true
Auth::hasRole('myapp-frontend', 'myapp-frontend-role1') // true
Auth::hasRole('myapp-backend', 'myapp-frontend-role1') // false


Twitter @robsontenorio

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.