Search by

sinemacula / laravel-authentication

sinemacula

Stateless contextual authentication primitives (Identity, Principal, Session, Tenant) for Laravel 12 and 13.

Package info

github.com/sinemacula/laravel-authentication

pkg:composer/sinemacula/laravel-authentication

Statistics

Installs: 4

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 2

dev-master 2026-11-01 05:45 UTC

README

Latest Stable Version PHP Version Laravel Version Build Status Quality Gates Maintainability Code Coverage Total Downloads License

Stateless contextual authentication for Laravel. Distinguishes the authenticated Identity from the acting Principal and the Session it signed in on, exposed through Laravel's standard Auth facade, middleware, and events.

Drops into Laravel's existing auth machinery - same Auth::check(), Auth::user(), auth()->guard('api'), same middleware, same events. Adds contextual accessors (Auth::identity(), Auth::principal(), Auth::session()) and ships a hardened JWT guard.

Core Concept

Concept What it is
Identity Who logged in. The account behind the request - a person or a service account.
Principal Who the request is acting as. Often the same as the identity; can be a role or membership.
Session One sign-in, on one application, on one device: a browser, a mobile app, a CLI. Refresh and revocation live here.
Tenant The isolation boundary the principal acts within. Optional, for multi-tenant apps.
Application The app being signed into, e.g. admin, console, mobile. Each application is a guard with its own methods and lifetimes.

Start 2D (the identity is the principal) and grow into 3D (identity → principal → tenant) without changing guards. Access tokens are self-verifying JWTs; refresh is stateful, held per session, so replays and revoked sessions are caught on the server.

Features

  • JWT guard with guard-bound, kid-rotated HMAC tokens, refresh rotation with replay detection, and a browser refresh cookie with CSRF checks.
  • Sign-in methods: password, one-time code to a phone or email, and passkeys, behind one contract that SSO and custom methods plug into.
  • Sessions: list, sign out, sign out everywhere, revoke on security changes, and switch principal.
  • Machine credentials: API keys and OAuth 2.0 client credentials for non-human identities, with scopes.
  • Account lifecycle: password policy, password reset, identifier verification and changing an email or phone.
  • Per-application settings: which sign-in methods and machine credentials each application allows (none until it lists them), whether identifiers must be verified, and its lifetimes.
  • Database rate limits, enumeration-resistant responses, and read-replica and Octane safety.
  • Events for every sign-in, refresh, revocation and failure, with one shared context and never a secret.
  • Localisable messages: the 401 and 429 messages translate through your lang/{locale}.json, and every other answer is a code your application words.
  • Extension points for MFA, authorisation, SSO and audit packages, each with a default that works without them.

Installation

composer require sinemacula/laravel-authentication

Configuration

Publish the config and the migrations, migrate, and generate a signing key:

php artisan vendor:publish --tag=authentication-config
php artisan vendor:publish --tag=authentication-migrations
php artisan migrate

echo "AUTHENTICATION_JWT_KEY=$(openssl rand -base64 48)" >> .env

Register a jwt guard and a model provider in config/auth.php. Each guard is an application, and allows only the sign-in methods it lists:

'guards' => [
    'api' => [
        'driver'      => 'jwt',
        'provider'    => 'users',
        'application' => ['methods' => ['password']],
    ],
],

'providers' => [
    'users' => [
        'driver' => 'model',
        'model'  => App\Models\AppUser::class,
    ],
],

See Installation for keys and providers, and Configuration for every option.

Usage

Give your user model the contracts and traits:

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Foundation\Auth\User;
use SineMacula\Laravel\Authentication\Concerns\ActsAsPrincipal;
use SineMacula\Laravel\Authentication\Concerns\Authenticatable;
use SineMacula\Laravel\Authentication\Contracts\HasSessions;
use SineMacula\Laravel\Authentication\Contracts\Identity;
use SineMacula\Laravel\Authentication\Contracts\Principal;
use SineMacula\Laravel\Authentication\Models\Session;

class AppUser extends User implements Identity, Principal, HasSessions
{
    use Authenticatable, ActsAsPrincipal;

    public function sessions(): MorphMany
    {
        return $this->morphMany(Session::class, 'authenticatable');
    }
}

Sign in through the guard's session service, and protect routes as with any Laravel guard:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use SineMacula\Laravel\Authentication\Facades\Auth;
use SineMacula\Laravel\Authentication\Sessions\SignInContext;

Route::post('/login', function (Request $request) {
    $credentials = $request->validate([
        'email'    => ['required', 'string'],
        'password' => ['required', 'string'],
    ]);

    $result = Auth::sessions('api')->signIn('password', $credentials, SignInContext::fromRequest($request));

    abort_unless($result->isSignedIn(), 401);

    return [
        'access_token'  => $result->session->tokens->accessToken,
        'refresh_token' => $result->session->tokens->refreshToken,
    ];
});

Route::middleware('auth:api')->get('/me', fn () => Auth::identity());

Guides

Guide Covers
Installation Keys, guards and providers, the 401, localisation, access-only mode
Identity models 2D and 3D models, identifiers, verification, activity
Signing in The session service, one-time codes, passkeys, custom methods, factors
Refreshing Refresh, the refresh cookie and replay detection
Sessions Switching principal, signing out, listing sessions and revocation
Passwords Password policy, setting a password and password reset
Changing identifiers Changing an email address or phone number
Machine credentials Non-human identities, scopes, API keys and client credentials
Events Every event, its context and the failure outcomes
Configuration Every configuration key
Operations Read replicas, Octane, key rotation, pruning and the configuration check
Testing Acting as an identity in your tests, context assertions and fakes
Extending Extension points and the MFA, authorisation, SSO and audit seams

The security and lifecycle contracts behind them, for maintainers and reviewers, are in docs/design.

Requirements

  • PHP ^8.3 (extensions: hash, mbstring, openssl; sodium, bundled with PHP, for EdDSA passkeys)
  • Laravel ^12.40 || ^13.3

Testing

composer test               # all suites in parallel (Paratest)
composer test:coverage      # all suites with clover coverage
composer test:unit          # unit suite only
composer test:feature       # feature suite only
composer test:integration   # integration suite only
composer test:performance   # performance budget suite (serial)
composer test:mutation      # scoped mutation gate
composer test:mutation:full # full mutation suite (no thresholds)
composer bench              # PHPBench hot-path benchmarks
composer check              # static analysis + style
composer format             # format the codebase
composer smells             # advisory code smells (duplication, complexity)

Changelog

See CHANGELOG.md for a list of notable changes.

Contributing

Contributions are welcome. Please read CONTRIBUTING.md for guidelines on branching, commits, code quality, and pull requests.

Security

If you discover a security vulnerability, please report it responsibly. See SECURITY.md for the disclosure policy and contact details.

License

Licensed under the Apache License, Version 2.0.