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

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

wg-hyve/keycloak-laravel-guard
==============================

Keycloak Guard for Laravel

0.8(1y ago)12.7k↓33.3%11MITPHPPHP ^8.2

Since Jun 22Pushed 1y ago1 watchersCompare

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

READMEChangelog (8)Dependencies (7)Versions (12)Used By (1)

Keycloak Laravel Implementation
===============================

[](#keycloak-laravel-implementation)

This Keycloak lib does not load users from database. Keycloak user UUIDs are usually stored in the sub claim.

Installation
------------

[](#installation)

```
composer require wg-hyve/keycloak-laravel-guard
```

Configuration
-------------

[](#configuration)

Add your keycloak to your guards and use it in your routes as middleware. That's it for a normal usage.

### config/auth.php

[](#configauthphp)

```
return [
    'guards' => [
        // ...
        'cloak' => [
            'driver' => 'keycloak',
            'provider' => 'users',
        ],
        // ...
    ],
];
```

### routes/api.php

[](#routesapiphp)

```
Route::any('/acme', [AcmeController::class, 'index'])->middleware(['auth:cloak']);
```

Extended usage
--------------

[](#extended-usage)

The KeycloakGuard comes with some methods to keep it easy.

### Example usage in requests

[](#example-usage-in-requests)

```
namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;

class DeleteRequest extends FormRequest
{
    public function authorize(): bool
    {
        return Auth::hasScope('can-delete');
    }

    public function rules(): array
    {
        return [];
    }
}
```

### Other Methods

[](#other-methods)

#### getTokenFromRequest

[](#gettokenfromrequest)

Get raw Token from request

#### token(): ?stdClass

[](#token-stdclass)

Get encoded Token from request

#### hasRole(array|string $roles): bool

[](#hasrolearraystring-roles-bool)

Proofs if the role or one of the roles is in your client or global roles

#### scopes(): array

[](#scopes-array)

Delivers all scopes

#### hasScope(string|array $scope): bool

[](#hasscopestringarray-scope-bool)

Proofs if the scope or one of the scopes is in your JWT

#### getRoles(): array

[](#getroles-array)

Delivers all roles from your client. Client is delivered in azp claim.

#### roles(bool $useGlobal = true): array

[](#rolesbool-useglobal--true-array)

Delivers all roles (global &amp; client)

User
----

[](#user)

Saving users in a local database is disabled per default. Execute following steps to enable it. Make sure you read the instructions for the environment variables in your `.env`.

### Configuration

[](#configuration-1)

Enable `KEYCLOAK_PROVIDE_LOCAL_USER` in your environment.

```
KEYCLOAK_PROVIDE_LOCAL_USER = true

```

The guard will save user objects from JWTs.

### Migrations

[](#migrations)

Publish und execute migrations.

```
php artisan vendor:publish --tag=keycloak-migrations
```

Make adjustments and migrate.

```
php artisan migrate
```

### User Model

[](#user-model)

Update your user model in `config/auth.php`. You can also extend it and add your own user model.

```
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => \KeycloakGuard\Models\User::class,
    ],
],
```

You are free to use your user model to extend and define custom relations. Make sure it is compatible with the migration above.

### Usage

[](#usage)

Receive the User instance with `user()`

```
namespace App\Your\Service

use Illuminate\Support\Facades\Auth;
use KeycloakGuard\Models\User;

class AcmeService
{
    public static function getUser(): ?User
    {
        return Auth::user();
    }
}
```

Environment Variables
---------------------

[](#environment-variables)

```
KEYCLOAK_REALM_PUBLIC_KEY

```

Local Public key of your Keycloak instance. You can find it in `https://your-keycloak.dev.com/auth/realms/your_realm/`

```
KEYCLOAK_TOKEN_PRINCIPAL_ATTRIBUTE

```

Should be `azp` or `client_id` depending on your Keycloak configuration

```
KEYCLOAK_IGNORE_RESOURCE_VALIDATION

```

true or false, auto check if role given with `KEYCLOAK_ALLOWED_RESOURCES` is in your token

```
KEYCLOAK_ALLOWED_RESOURCES

```

role to auto check

```
KEYCLOAK_REALM_ADDRESS

```

URL to load public key. Usually `https://your-keycloak.dev.com/auth/realms/your_realm/`

```
KEYCLOAK_KEY_CACHE_SECONDS

```

Cache duration for downloaded public key of your realm.

```
KEYCLOAK_LEEWAY

```

You want to set the time offset in seconds if you get `Cannot handle token prior to (time) error`. Use this if your app and Keycloak timings differ.

```
KEYCLOAK_PROVIDE_LOCAL_USER

```

Enable local user processing. The guard will try to store the user in a local database. Default is false.

```
KEYCLOAK_USER_ID_CLAIM

```

The user UUID in your JWT. Default is sub claim.

```
KEYCLOAK_USER_MAIL_CLAIM

```

The email claim in your JWT. Default is email.

```
KEYCLOAK_USER_FIRSTNAME_CLAIM

```

The firstname claim in your JWT. Default is given\_name.

```
KEYCLOAK_USER_LASTNAME_CLAIM

```

The lastname claim in your JWT. Default is family\_name.

Testing
-------

[](#testing)

### Commands

[](#commands)

```
# run tests with testdox
composer test

# run tests with coverage
composer test:coverage
```

### Docker

[](#docker)

Test in docker with coverage after you extended to lib. Don't install xdebug locally 🐌

### Create a new source JSON file

[](#create-a-new-source-json-file)

Source files are stored in `tests/Data`Generated tokens are stored in `tests/Data/tokens`

```
composer jwt:generate jwt.json access_token
composer jwt:generate jwt_realm_access.json access_token_realm_access
composer jwt:generate jwt.json access_token_has_expire true
```

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance33

Infrequent updates — may be unmaintained

Popularity23

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 60% 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 ~56 days

Recently: every ~97 days

Total

8

Last Release

658d ago

PHP version history (2 changes)0.1PHP ^8.1

0.6PHP ^8.2

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/32953220?v=4)[Dennis Falkenberg](/maintainers/Falki141)[@Falki141](https://github.com/Falki141)

---

Top Contributors

[![SineMah](https://avatars.githubusercontent.com/u/8180962?v=4)](https://github.com/SineMah "SineMah (33 commits)")[![Falki141](https://avatars.githubusercontent.com/u/32953220?v=4)](https://github.com/Falki141 "Falki141 (22 commits)")

---

Tags

keycloaklaravelphplaravelkeycloak

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[lab404/laravel-impersonate

Laravel Impersonate is a plugin that allows to you to authenticate as your users.

2.3k16.4M48](/packages/lab404-laravel-impersonate)[robsontenorio/laravel-keycloak-guard

🔑 Simple Keycloak Guard for Laravel

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

PHPackages © 2026

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