PHPackages                             tysonm/laravel-keycloak-guard - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. tysonm/laravel-keycloak-guard

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

tysonm/laravel-keycloak-guard
=============================

🔑 Simple Keycloak Guard for Laravel 10 and keycloack 22

1.0.0(2y ago)045MITPHPPHP ^8.1

Since Nov 21Pushed 2y agoCompare

[ Source](https://github.com/tysonm/laravel-keycloak-guard)[ Packagist](https://packagist.org/packages/tysonm/laravel-keycloak-guard)[ Docs](https://github.com/tysonm/laravel-keycloak-guard)[ RSS](/packages/tysonm-laravel-keycloak-guard/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (6)Versions (2)Used By (0)

 [![](bird.png)](bird.png)

 [![](https://camo.githubusercontent.com/c59cbddffe2833843d413d748e720118bf0ff2f1575a1d778f93256648b6a268/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f726f62736f6e74656e6f72696f2f6c61726176656c2d6b6579636c6f616b2d67756172642e737667)](https://camo.githubusercontent.com/c59cbddffe2833843d413d748e720118bf0ff2f1575a1d778f93256648b6a268/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f726f62736f6e74656e6f72696f2f6c61726176656c2d6b6579636c6f616b2d67756172642e737667) [![](https://camo.githubusercontent.com/43340c432c1338eb6692ff2acfea404c2fc4c46eeabfabf142b060fdc01aff86/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f726f62736f6e74656e6f72696f2f6c61726176656c2d6b6579636c6f616b2d67756172642e737667)](https://camo.githubusercontent.com/43340c432c1338eb6692ff2acfea404c2fc4c46eeabfabf142b060fdc01aff86/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f726f62736f6e74656e6f72696f2f6c61726176656c2d6b6579636c6f616b2d67756172642e737667) [![](https://camo.githubusercontent.com/c9123752b96356a82459bad9ee2dfc37b4cfd0e79357fde567f29a3f8cb05389/68747470733a2f2f636f6465636f762e696f2f67682f726f62736f6e74656e6f72696f2f6c61726176656c2d6b6579636c6f616b2d67756172642f6272616e63682f6d61737465722f67726170682f62616467652e7376673f746f6b656e3d385a7044617270737331)](https://camo.githubusercontent.com/c9123752b96356a82459bad9ee2dfc37b4cfd0e79357fde567f29a3f8cb05389/68747470733a2f2f636f6465636f762e696f2f67682f726f62736f6e74656e6f72696f2f6c61726176656c2d6b6579636c6f616b2d67756172642f6272616e63682f6d61737465722f67726170682f62616467652e7376673f746f6b656e3d385a7044617270737331)

Simple Keycloak Guard for Laravel
=================================

[](#simple-keycloak-guard-for-laravel)

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

Requirements
============

[](#requirements)

✔️ 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  or

The flow
========

[](#the-flow)

 [![](flow.png)](flow.png)

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, then find the user on database and authenticate it on my API.
6. Optionally, the user can be created / updated in the API users database.
7. Return response

Install
=======

[](#install)

### Laravel / Lumen

[](#laravel--lumen)

Require the package

```
composer require tysonm/laravel-keycloak-guard

```

### Lumen only

[](#lumen-only)

Register the provider in your boostrap app file `bootstrap/app.php`

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

```
$app->register(\KeycloakGuard\KeycloakGuardServiceProvider::class);
```

For facades, uncomment `$app->withFacades();` in your boostrap app file `bootstrap/app.php`

Configuration
=============

[](#configuration)

Keycloak Guard
--------------

[](#keycloak-guard)

⚠️ When editing `.env` make sure all strings **are trimmed.**

```
# Publish config file

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

✔️ **realm\_public\_key**

*Required.*

The Keycloak Server realm public key (string).

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

✔️ **load\_user\_from\_database**

*Required. Default is `true`.*

If you do not have an `users` table you must disable this.

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

✔️ **user\_provider\_custom\_retrieve\_method**

*Default is `null`.*

If you have an `users` table and want it to be updated (creating or updating users) based on the token, you can inform a custom method on a custom UserProvider, that will be called instead `retrieveByCredentials` and will receive the complete decoded token as parameter, not just the credentials (as default). This will allow you to customize the way you want to interact with your database, before matching and delivering the authenticated user object, having all the information contained in the (valid) access token available. To read more about custom UserProviders, please check [Laravel's documentation about](https://laravel.com/docs/10.x/authentication#adding-custom-user-providers).

If using this feature, obviously, values defined for `user_provider_credential` and `token_principal_attribute` will be ignored.

✔️ **user\_provider\_email\_credential**

*Required. Default is `username`.*

The field from "users" table that contains the other unique identifier (eg. username, email, nickname) that is not in user\_provider\_credential. This will be confronted against `token_principal_attribute` attribute, while authenticating. ✔️ **user\_provider\_credential**

*Required. Default is `username`.*

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

✔️ **token\_principal\_attribute**

*Required. Default is `preferred_username`.*

The property from JWT token that contains the user identifier. This will be confronted against `user_provider_credential` attribute, while authenticating.

✔️ **append\_decoded\_token**

*Default is `false`.*

Appends to the authenticated user the full decoded JWT token (`$user->token`). Useful if you need to know roles, groups and other user info holded by JWT token. Even choosing `false`, you can also get it using `Auth::token()`, see API section.

✔️ **allowed\_resources**

*Required*.

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 `resource_access` attribute from JWT token, while authenticating.

✔️ **ignore\_resources\_validation**

*Default is `false`*.

Disables entirely resources validation. It will **ignore** *allowed\_resources* configuration.

✔️ **leeway**

*Default is `0`*.

You can add a leeway to account for when there is a clock skew times between the signing and verifying servers. If you are facing issues like *"Cannot handle token prior to "* try to set it `60` (seconds).

✔️ **input\_key**

*Default is `null`.*

By default this package **always** will look at first for a `Bearer` token. Additionally, if this option is enabled, then it will try to get a token from this custom request param.

```
// keycloak.php
'input_key' => 'api_token'

// If there is no Bearer token on request it will use `api_token` request param
GET  $this->get("/foo/secret?api_token=xxxxx")
POST $this->post("/foo/secret", ["api_token" => "xxxxx"])
```

Laravel Auth
------------

[](#laravel-auth)

Changes on `config/auth.php`

```
...
'defaults' => [
        'guard' => 'api', #  'users',
    ],

    ....

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

Laravel Routes
--------------

[](#laravel-routes)

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

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

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

Lumen Routes
------------

[](#lumen-routes)

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

```
// public endpoints
$router->get('/hello', function () {
    return ':)';
});

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

API
===

[](#api)

Simple Keycloak Guard implements `Illuminate\Contracts\Auth\Guard`. So, all Laravel default methods will be available.

Default Laravel methods
-----------------------

[](#default-laravel-methods)

- `check()`
- `guest()`
- `user()`
- `id()`
- `validate()`
- `setUser()`

Keycloak Guard methods
----------------------

[](#keycloak-guard-methods)

`token()`*Returns full decoded JWT token from authenticated user.*

```
$token = Auth::token()  // or Auth::user()->token()
```

`hasRole('some-resource', 'some-role')`*Check if authenticated user has a role on resource\_access*

```
// Example decoded payload

'resource_access' => [
  'myapp-backend' => [
      'roles' => [
        'myapp-backend-role1',
        'myapp-backend-role2'
      ]
  ],
  'myapp-frontend' => [
    'roles' => [
      'myapp-frontend-role1',
      'myapp-frontend-role2'
    ]
  ]
]
```

```
Auth::hasRole('myapp-backend', 'myapp-backend-role1') // true
Auth::hasRole('myapp-frontend', 'myapp-frontend-role1') // true
Auth::hasRole('myapp-backend', 'myapp-frontend-role1') // false
```

`hasAnyRole('some-resource', ['some-role1', 'some-role2'])`*Check if the authenticated user has any of the roles in resource\_access*

```
Auth::hasAnyRole('myapp-backend', ['myapp-backend-role1', 'myapp-backend-role3']) // true
Auth::hasAnyRole('myapp-frontend', ['myapp-frontend-role1', 'myapp-frontend-role3']) // true
Auth::hasAnyRole('myapp-backend', ['myapp-frontend-role1', 'myapp-frontend-role2']) // false
```

Contribute
==========

[](#contribute)

You can run this project on VSCODE with Remote Container. Make sure you will use internal VSCODE terminal (inside running container).

```
composer install
composer test
composer test:coverage
```

Contact
=======

[](#contact)

Twitter [@robsontenorio](https://twitter.com/robsontenorio)

###  Health Score

25

—

LowBetter than 37% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 72.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

903d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/8e91e7845420185fa5f13d674516645f01446e057e6fc8a5aafc47f07f791e42?d=identicon)[tysonm](/maintainers/tysonm)

---

Top Contributors

[![robsontenorio](https://avatars.githubusercontent.com/u/118955?v=4)](https://github.com/robsontenorio "robsontenorio (24 commits)")[![frital](https://avatars.githubusercontent.com/u/17753531?v=4)](https://github.com/frital "frital (1 commits)")[![luizjr](https://avatars.githubusercontent.com/u/1474563?v=4)](https://github.com/luizjr "luizjr (1 commits)")[![matsver](https://avatars.githubusercontent.com/u/42805709?v=4)](https://github.com/matsver "matsver (1 commits)")[![OfficialBAMM](https://avatars.githubusercontent.com/u/10955512?v=4)](https://github.com/OfficialBAMM "OfficialBAMM (1 commits)")[![peter279k](https://avatars.githubusercontent.com/u/9021747?v=4)](https://github.com/peter279k "peter279k (1 commits)")[![ptrgast](https://avatars.githubusercontent.com/u/10983711?v=4)](https://github.com/ptrgast "ptrgast (1 commits)")[![roberto-proj](https://avatars.githubusercontent.com/u/121515667?v=4)](https://github.com/roberto-proj "roberto-proj (1 commits)")[![antonkomarev](https://avatars.githubusercontent.com/u/1849174?v=4)](https://github.com/antonkomarev "antonkomarev (1 commits)")[![SolveSoul](https://avatars.githubusercontent.com/u/6033289?v=4)](https://github.com/SolveSoul "SolveSoul (1 commits)")

###  Code Quality

TestsPest

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/tysonm-laravel-keycloak-guard/health.svg)

```
[![Health](https://phpackages.com/badges/tysonm-laravel-keycloak-guard/health.svg)](https://phpackages.com/packages/tysonm-laravel-keycloak-guard)
```

###  Alternatives

[google/auth

Google Auth Library for PHP

1.4k272.7M162](/packages/google-auth)[thenetworg/oauth2-azure

Azure Active Directory OAuth 2.0 Client Provider for The PHP League OAuth2-Client

2509.6M48](/packages/thenetworg-oauth2-azure)[stevenmaguire/oauth2-keycloak

Keycloak OAuth 2.0 Client Provider for The PHP League OAuth2-Client

2275.9M27](/packages/stevenmaguire-oauth2-keycloak)[robsontenorio/laravel-keycloak-guard

🔑 Simple Keycloak Guard for Laravel

5161.1M3](/packages/robsontenorio-laravel-keycloak-guard)[patrickbussmann/oauth2-apple

Sign in with Apple OAuth 2.0 Client Provider for The PHP League OAuth2-Client

1132.5M6](/packages/patrickbussmann-oauth2-apple)[wp-graphql/wp-graphql-jwt-authentication

JWT Authentication for WPGraphQL

361118.4k1](/packages/wp-graphql-wp-graphql-jwt-authentication)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
