Download the PHP package ez-php/auth without Composer
On this page you can find all versions of the php package ez-php/auth. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Package auth
Short Description Authentication module for the ez-php framework — session and token-based auth with a flexible user provider interface
License MIT
Homepage https://github.com/ez-php/auth
Informations about the package auth
ez-php/auth
Authentication module for the ez-php framework — session, Bearer token, JWT, and personal access token authentication with a flexible user provider interface.
Requirements
- PHP 8.5+
- ez-php/framework 0.*
Installation
Setup
Register the service provider in your application:
Implement UserProviderInterface to connect your user storage:
Your user class implements UserInterface: getAuthId() (the identifier stored in the
session) and getAuthPassword() (the password_hash() hash Auth::attempt() verifies against).
Bind it before AuthServiceProvider:
Usage
Session / Bearer token authentication
AuthMiddleware checks Authorization: Bearer <token> against the bound UserProviderInterface
(findByToken()), or against a static token list when constructed as
new AuthMiddleware(['api-key-1', 'api-key-2']). With neither — e.g. registered by class name
while no UserProviderInterface is bound — it rejects every request with 401 instead of
letting any token through.
Remember me
Auth::loginWithRemember($user) logs the user in and returns a random raw token. The module
does not persist it for you — the application stores it, and findByRememberToken() reads it back:
Store and compare only hash('sha256', $token) — a leaked database then yields no usable
cookie values. findByRememberToken() receives the raw cookie value precisely so the provider
does the hashing at the lookup. Rotate the stored hash on every remember-login and clear it on
logout.
The hash loginWithRemember() also writes to $_SESSION['auth_remember_token'] is a
same-session check only: Auth::verifyRememberToken($token) confirms that a presented cookie
was issued in this session (e.g. before a sensitive action). It cannot restore a login after
the session has ended — that is what the persisted hash and attemptRemember() are for.
JWT authentication
JwtServiceProvider reads auth.jwt.secret / auth.jwt.ttl (the template's config/auth.php,
backed by these variables) and falls back to the variables themselves when a key is unset.
The secret is required: resolving JwtManager throws when it is unset or shorter than
32 bytes (JwtManager::MIN_SECRET_BYTES, the HS256 minimum from RFC 7518), instead of
signing with an empty key that would let anyone forge tokens.
Rate-limited login attempts
For per-route throttling,
compose ez-php/rate-limiter's ThrottleMiddleware in front of your login route instead,
passing the route's limit as middleware parameters (maxAttempts,decaySeconds[,bucket]):
Auth's static-façade design is untouched by this — the throttle lives entirely in the
middleware chain in front of it.
To throttle failed logins per user (not per route) and tell the client why a login failed,
use LoginThrottle inside the controller:
A success logs the user in and resets the counter; the failed-attempt lockout is
independent of Auth::attempt(), which keeps returning a plain bool.
Session guard for routes
SessionAuthMiddleware lets a request through only when a user is logged in via the session
(Auth::check()), otherwise it answers 401 — JSON ({"error":{"code":401,...}}) for clients
sending Accept: application/json. Pass a closure to build the response yourself:
Example login/register scaffold
auth:scaffold writes a starting-point login/register/logout controller and routes file:
Creates:
app/Controllers/AuthController.php—login()/register()/logout()built onAuth::login()/hashPassword()/verifyPassword()routes/auth.php— the matchingPOST /login,POST /register,POST /logoutroutes
Require the routes file from routes/web.php to activate it:
Refuses to run if AuthController.php already exists. Not a complete user-management system —
findUserByEmail()/createUser() in the generated controller throw RuntimeException until
you replace them with your application's actual user lookup/persistence; ez-php/auth has no
user model or schema to generate those against.
Register the command before bootstrap, same as auth:token:
Personal access tokens
One-time tokens for e-mail verification or password reset live in the same table but are bound to one purpose, work once, and never authenticate as a Bearer token:
To revoke every regular token of a user with a given name — e.g. all rotating refresh
tokens after a password reset — use revokeNamed(). It never touches one-time tokens:
When an account is deleted, revokeAllFor($userId) removes all of its tokens — regular and
one-time. Token records hand userId back as an int when the stored id is a plain number
(PDO returns MySQL integers as strings); string ids such as UUIDs are left as they are.
Register the bundled migration before migrating:
Console command
--abilities defaults to * (all abilities); omit --expires for a token that never expires.
The command is opt-in — AuthServiceProvider does not register it, since issuing tokens from
the CLI should be a deliberate choice. Register it before bootstrap:
Classes
| Class | Description |
|---|---|
Auth |
Static façade — login(), logout(), user(), check(), id(), hashPassword(), verifyPassword(), dummyPasswordHash() (verify an unknown user's password against it so the timing doesn't reveal which accounts exist) |
AuthServiceProvider |
Registers Auth singleton; optionally injects UserProviderInterface |
UserInterface |
Contract for authenticated user objects — getAuthId(), getAuthPassword() |
UserProviderInterface |
Contract for user lookup — findById(), findByToken(), findByCredentials(), findByRememberToken() |
AuthorizableInterface |
Optional contract for authorization checks on user objects |
PersonalAccessToken |
Immutable value object — isExpired(), can() |
PersonalAccessTokenManager |
Token CRUD — create(), find(), revoke(), rotate(), pruneExpired(); revokeNamed(), revokeAllFor(); one-time tokens — issueOneTime(), consume(), revokeFor() |
AuthMiddleware |
Bearer token middleware (static list or provider mode) |
SessionAuthMiddleware |
Session guard — 401 (plain or JSON) unless Auth::check(), optional response closure |
LoginThrottle / LoginResult |
Throttled login returning success / invalid / locked out (availableIn) with a caller-supplied key |
JwtMiddleware |
JWT Bearer token middleware with optional blacklist and user resolution |
JwtManager |
Issues and validates HMAC-HS256 JWTs |
JwtBlacklist |
Cache-backed token blacklist (SHA-256 keyed) |
JwtServiceProvider |
Registers JwtManager and JwtBlacklist |
Console\TokenCommand |
auth:token CLI command |
Console\AuthScaffoldCommand |
auth:scaffold CLI command — example login/register controller + routes |
License
MIT — Andreas Uretschnig
All versions of auth with dependencies
ez-php/contracts Version ^2.7.0
ez-php/cache Version ^2.7.0
ez-php/console Version ^2.7.0
ez-php/http Version ^2.7.0
ez-php/rate-limiter Version ^2.7.0