PHPackages                             fmiqbal/laravel-kratos-auth - 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. fmiqbal/laravel-kratos-auth

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

fmiqbal/laravel-kratos-auth
===========================

Laravel Auth Guard for Ory Kratos

1.2.3(1y ago)05MITPHPPHP ^8.1

Since Mar 18Pushed 1y ago1 watchersCompare

[ Source](https://github.com/fmiqbal/laravel-kratos-auth)[ Packagist](https://packagist.org/packages/fmiqbal/laravel-kratos-auth)[ RSS](/packages/fmiqbal-laravel-kratos-auth/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (4)Versions (9)Used By (0)

Laravel Kratos Auth
===================

[](#laravel-kratos-auth)

This package is to add Guard for [Ory Kratos](https://github.com/ory/kratos). The guard will call Ory Kratos `/sessions/whoami` endpoint and built an ephemeral user based on that.

> This package is only meant to be used for **self-hosted Ory Kratos**

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

[](#installation)

```
composer require fmiqbal/laravel-kratos-auth
```

Quick Start
-----------

[](#quick-start)

1. Add `kratos` driver to your auth guard in `config/auth.php`

```
        'web' => [
            'driver' => 'kratos',
        ],
```

> **Note:** This driver does **not** use Laravel native `UserProvider`, assuming that user data is managed externally in Ory Kratos. However, you can implement custom mapping (e.g., user discovery, database syncing).

2. Set the env var

Add the Kratos URL to your .env file.

```
KRATOS_URL=https://your-kratos-public-url:4445
```

> **Note:** You should use Kratos Public URL because this package only calls self-service not the admin Url.

3. Test Authentication

Create a test route to inspect the authenticated user:

```
Route::middleware('auth')->get('/user', function (\Illuminate\Http\Request $request) {
    dd(
        $request->user(),
        \Illuminate\Support\Facades\Auth::user(),
    );
});
```

By default, the authenticated user does not persist in a database. You can customize this behavior using `user_scaffold` in the configuration

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

[](#configuration)

You can publish the configuration file (config/kratos.php) using:

```
php artisan vendor:publish --provider "Fmiqbal\KratosAuth\ServiceProvider"
```

Most configuration options are available via environment variables (ENV).

### User Scaffolding

[](#user-scaffolding)

The user scaffold determines how the Auth::user() method constructs a user object. By default, a generic Laravel Authenticatable instance is returned (`\Illuminate\Auth\GenericUser`)

However, **you should customize this function** to fit your needs.

#### Example 1: Creating Users in the Database

[](#example-1-creating-users-in-the-database)

```
    'user_scaffold' => static function (\Ory\Kratos\Client\Model\Session $session) {
        return \App\Models\User::unguarded(
            static fn() => \App\Models\User::firstOrCreate([
                'guid' => $session->getIdentity()?->getId(),
            ], [
                'name' => $session->getIdentity()?->getTraits()->name,
                'picture' => $session->getIdentity()?->getTraits()->picture,
                'email' => $session->getIdentity()?->getTraits()->email,
                'email_verified_at' => \Carbon\Carbon::now()->timestamp,
            ])
        );
    },
```

> **Warning:** this method will be called on **every request**, just like UserProvider.

#### Example 2: Using Cache for Performance

[](#example-2-using-cache-for-performance)

To avoid database hits on every request, you can cache user data:

```
'user_scaffold' => static function (\Ory\Kratos\Client\Model\Session $session) {
    $id = $session->getIdentity()->getId();

    return Cache::remember("user:$id", 300, function () use ($id) {
        return \App\Models\User::find($id);
    });
},
```

> **Note:** This caches user data for 5 minutes (300s) to reduce DB queries.

#### Example 3: Rejecting Unrecognized Users

[](#example-3-rejecting-unrecognized-users)

If you want to reject users who are not found in your system, return null:

```
'user_scaffold' => static function (\Ory\Kratos\Client\Model\Session $session) {
    return \App\Models\User::find($session->getIdentity()?->getId());
},
```

> This will throw an `AuthenticationException` if the user does not exist.

### Caching

[](#caching)

This package supports session caching, which helps reduce Ory Kratos API calls.

- Enable caching by setting:

```
KRATOS_CACHE_ENABLED=true
```

- Default TTL (Time-to-Live) is 300 seconds.
- Each session is keyed by the hashed session cookie.
- The cookie name (in case you change it from default `ory_kratos_session`) is available via:

```
KRATOS_SESSION_COOKIE_NAME=my_kratos_session
```

> **Note:** This does not cache users—you must implement that separately in user\_scaffold.

### Customizing the Guzzle Client

[](#customizing-the-guzzle-client)

If you need to modify the HTTP client (e.g., for Sentry tracing), you can override the default Guzzle Client like this:

```
    'guzzle_client' => static function () {
        $stack = new \GuzzleHttp\HandlerStack();
        $stack->setHandler(new \GuzzleHttp\Handler\CurlHandler());
        $stack->push(\Sentry\Tracing\GuzzleTracingMiddleware::trace());

        return new GuzzleHttp\Client(['handler' => $stack]);
    },
```

Capability
----------

[](#capability)

This package support following `Auth::` common facade method, that extended from `GuardHelpers` + `logout()`

```
Auth::id();
Auth::validate();
Auth::user();
Auth::logout();
```

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance46

Moderate activity, may be stable

Popularity4

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~1 days

Total

8

Last Release

415d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/108c9612dae54491a909f490123cd0063cd6710adae88a07da2f34fcaf539079?d=identicon)[fmiqbal](/maintainers/fmiqbal)

---

Top Contributors

[![fmiqbal](https://avatars.githubusercontent.com/u/8409391?v=4)](https://github.com/fmiqbal "fmiqbal (35 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/fmiqbal-laravel-kratos-auth/health.svg)

```
[![Health](https://phpackages.com/badges/fmiqbal-laravel-kratos-auth/health.svg)](https://phpackages.com/packages/fmiqbal-laravel-kratos-auth)
```

###  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)[santigarcor/laratrust

This package provides a flexible way to add Role-based Permissions to Laravel

2.3k5.4M43](/packages/santigarcor-laratrust)[overtrue/laravel-follow

User follow unfollow system for Laravel.

1.2k404.7k5](/packages/overtrue-laravel-follow)[codegreencreative/laravel-samlidp

Make your PHP Laravel application an Identification Provider using SAML 2.0. This package allows you to implement your own Identification Provider (idP) using the SAML 2.0 standard to be used with supporting SAML 2.0 Service Providers (SP).

263763.5k1](/packages/codegreencreative-laravel-samlidp)

PHPackages © 2026

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