PHPackages                             tecnical/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. tecnical/laravel-keycloak-guard

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

tecnical/laravel-keycloak-guard
===============================

Keycloak Guard for Laravel

2.0.4(1y ago)018MITPHPPHP ^8.0

Since Jul 20Pushed 1y agoCompare

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

READMEChangelogDependencies (6)Versions (27)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)

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

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

This package is a fork of

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 robsontenorio/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 (or defined under token\_encryption\_algorithm configuration)" Line &gt; "Public Key" Button

✔️ **token\_encryption\_algorithm**

*Default is `RS256`.*

The JWT token encryption algorithm used by Keycloak (string).

✔️ **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/8.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\_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

[](#token)

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

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

#### Role

[](#role)

`hasResourceRole('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::hasResourceRole('myapp-backend', 'myapp-backend-role1') // true
Auth::hasResourceRole('myapp-frontend', 'myapp-frontend-role1') // true
Auth::hasResourceRole('myapp-backend', 'myapp-frontend-role1') // false
```

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

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

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

```
Auth::hasRealmRole('myapp-backend-role1') // true
Auth::hasRealmRole('myapp-frontend-role1') // true
```

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

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

#### Scope

[](#scope)

Example decoded payload:

```
{
    "scope": "scope-a scope-b scope-c",
}
```

`scopes()`*Get all user scopes*

```
array:3 [
  0 => "scope-a"
  1 => "scope-b"
  2 => "scope-c"
]
```

`hasScope('some-scope')`*Check if authenticated user has a scope*

```
Auth::hasScope('scope-a') // true
Auth::hasScope('scope-d') // false
```

`hasAnyScope(['scope-a', 'scope-c'])`*Check if the authenticated user has any of the scopes*

```
Auth::hasAnyScope(['scope-a', 'scope-c']) // true
Auth::hasAnyScope(['scope-a', 'scope-d']) // true
Auth::hasAnyScope(['scope-f', 'scope-k']) // false
```

Acting as a Keycloak user in tests
----------------------------------

[](#acting-as-a-keycloak-user-in-tests)

As an equivalent feature like `$this->actingAs($user)` in Laravel, with this package you can use `KeycloakGuard\ActingAsKeycloakUser` trait in your test class and then use `actingAsKeycloakUser()` method to act as a user and somehow skip the Keycloak auth:

```
use KeycloakGuard\ActingAsKeycloakUser;

public test_a_protected_route()
{
    $this->actingAsKeycloakUser()
        ->getJson('/api/somewhere')
        ->assertOk();
}
```

If you are not using `keycloak.load_user_from_database` option, set `keycloak.preferred_username` with a valid `preferred_username` for tests.

You can also specify exact expectations for the token payload by passing the payload array in the second argument:

```
use KeycloakGuard\ActingAsKeycloakUser;

public test_a_protected_route()
{
    $this->actingAsKeycloakUser($user, [
        'aud' => 'account',
        'exp' => 1715926026,
        'iss' => 'https://localhost:8443/realms/master'
    ])->getJson('/api/somewhere')
      ->assertOk();
}
```

`$user` argument receives a string identifier or an Eloquent model, identifier of which is expected to be the property referred in **user\_provider\_credential** config. Whatever you pass in the payload will override default claims, which includes `aud`, `iat`, `exp`, `iss`, `azp`, `resource_access` and either `sub` or `preferred_username`, depending on **token\_principal\_attribute** config.

Alternatively, payload can be provided in a class property, so it can be reused across multiple tests:

```
use KeycloakGuard\ActingAsKeycloakUser;

protected $tokenPayload = [
    'aud' => 'account',
    'exp' => 1715926026,
    'iss' => 'https://localhost:8443/realms/master'
];

public test_a_protected_route()
{
    $payload = [
        'exp' => 1715914352
    ];
    $this->actingAsKeycloakUser($user, $payload)
        ->getJson('/api/somewhere')
        ->assertOk();
}
```

Priority is given to the claims in passed as an argument, so they will override ones in the class property. `$user` argument has the highest priority over the claim referred in **token\_principal\_attribute** config.

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

35

—

LowBetter than 80% of packages

Maintenance31

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity78

Established project with proven stability

 Bus Factor1

Top contributor holds 61.5% 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

Every ~93 days

Recently: every ~0 days

Total

24

Last Release

713d ago

Major Versions

1.6.1 → 2.0.02024-05-29

### Community

Maintainers

![](https://www.gravatar.com/avatar/f9cbaa25dff145cff3892ad8cb3b55f2f665c322be8e68d27a4c01e3200216ca?d=identicon)[tecnical](/maintainers/tecnical)

---

Top Contributors

[![robsontenorio](https://avatars.githubusercontent.com/u/118955?v=4)](https://github.com/robsontenorio "robsontenorio (24 commits)")[![vlauciani](https://avatars.githubusercontent.com/u/16477095?v=4)](https://github.com/vlauciani "vlauciani (2 commits)")[![elnurvl](https://avatars.githubusercontent.com/u/7970970?v=4)](https://github.com/elnurvl "elnurvl (1 commits)")[![frital](https://avatars.githubusercontent.com/u/17753531?v=4)](https://github.com/frital "frital (1 commits)")[![hamidhaghdoost](https://avatars.githubusercontent.com/u/8298095?v=4)](https://github.com/hamidhaghdoost "hamidhaghdoost (1 commits)")[![luizjr](https://avatars.githubusercontent.com/u/1474563?v=4)](https://github.com/luizjr "luizjr (1 commits)")[![marwins](https://avatars.githubusercontent.com/u/20090626?v=4)](https://github.com/marwins "marwins (1 commits)")[![Androbin](https://avatars.githubusercontent.com/u/16437156?v=4)](https://github.com/Androbin "Androbin (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)")[![SolveSoul](https://avatars.githubusercontent.com/u/6033289?v=4)](https://github.com/SolveSoul "SolveSoul (1 commits)")[![matsver](https://avatars.githubusercontent.com/u/42805709?v=4)](https://github.com/matsver "matsver (1 commits)")[![antonkomarev](https://avatars.githubusercontent.com/u/1849174?v=4)](https://github.com/antonkomarev "antonkomarev (1 commits)")

---

Tags

laravelkeycloak

###  Code Quality

TestsPest

Code StylePHP CS Fixer

### Embed Badge

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

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

###  Alternatives

[robsontenorio/laravel-keycloak-guard

🔑 Simple Keycloak Guard for Laravel

5161.1M3](/packages/robsontenorio-laravel-keycloak-guard)[vizir/laravel-keycloak-web-guard

Simple Keycloak Guard to Laravel Web Routes

166574.1k](/packages/vizir-laravel-keycloak-web-guard)[socialiteproviders/microsoft

Microsoft OAuth2 Provider for Laravel Socialite

326.1M13](/packages/socialiteproviders-microsoft)

PHPackages © 2026

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