authxi / laravel
Sign in to Laravel apps through authxi (OpenID Connect): login routes, a provider for your own controllers, step-up two-step verification and middleware.
Requires
- php: ^8.2
- firebase/php-jwt: ^6.10|^7.0
- illuminate/auth: ^11.0|^12.0|^13.0
- illuminate/cache: ^11.0|^12.0|^13.0
- illuminate/contracts: ^11.0|^12.0|^13.0
- illuminate/database: ^11.0|^12.0|^13.0
- illuminate/hashing: ^11.0|^12.0|^13.0
- illuminate/http: ^11.0|^12.0|^13.0
- illuminate/routing: ^11.0|^12.0|^13.0
- illuminate/session: ^11.0|^12.0|^13.0
- illuminate/support: ^11.0|^12.0|^13.0
Requires (Dev)
- orchestra/testbench: ^9.0|^10.0|^11.0
- phpunit/phpunit: ^11.5|^12.0|^13.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
authxi/laravel
Sign people in to a Laravel app through authxi. The package gives you:
- Optional routes (
/auth/login,/auth/callback,/auth/logout) that sign the user in to your guard, so you don't write a callback controller. Authxi::provider()for your own controllers: OpenID Connect code flow with PKCE S256,stateandnonce, and an RS256 ID token verified against the workspace's JWKS.- Step-up two-step verification:
Authxi::stepUp(),Authxi::verifiedWithin()and theauthxi.verifiedmiddleware.
Laravel 11, 12 and 13, PHP 8.2 or newer. No other sign-in package is needed.
Install
composer require authxi/laravel
php artisan vendor:publish --tag=authxi-migrations # adds a nullable unique users.authxi_id
php artisan migrate
In the authxi dashboard, create a web application and register:
- the callback URL, for example
https://app.example.com/auth/callback - the post-logout URL, for example
https://app.example.com/
Configure
.env:
AUTHXI_ISSUER=https://acme.authxi.com AUTHXI_CLIENT_ID=app_... AUTHXI_CLIENT_SECRET=... AUTHXI_REDIRECT_URI=https://app.example.com/auth/callback AUTHXI_POST_LOGOUT_REDIRECT_URI=https://app.example.com/
That is enough. If you keep OAuth settings in config/services.php, values there take precedence:
'authxi' => [ 'issuer' => env('AUTHXI_ISSUER'), 'client_id' => env('AUTHXI_CLIENT_ID'), 'client_secret' => env('AUTHXI_CLIENT_SECRET'), 'redirect' => env('AUTHXI_REDIRECT_URI'), ],
redirect defaults to the package's /auth/callback route, and a relative path is made absolute with APP_URL.
The other settings (routes, guard, home page, user model, caching) are in config/authxi.php:
php artisan vendor:publish --tag=authxi-config.
Quickstart
// bootstrap/app.php: send guests to authxi ->withMiddleware(function (Middleware $middleware) { $middleware->redirectGuestsTo(fn () => route('authxi.login')); }) // routes/web.php Route::get('/billing', BillingController::class)->middleware('auth'); Route::post('/payouts', PayoutController::class)->middleware(['auth', 'authxi.verified:300']);
@if (session('authxi_error')) <p role="alert">{{ session('authxi_error') }}</p> @endif @auth <form method="POST" action="{{ route('authxi.logout') }}">@csrf <button>Sign out</button></form> @else <a href="{{ route('authxi.login', ['returnTo' => request()->getRequestUri()]) }}">Sign in</a> @endauth
A guest who opens /billing?tab=due goes to authxi, signs in with Google and lands back on /billing?tab=due.
Routes
| Route | Name | Does |
|---|---|---|
GET /auth/login?returnTo=/billing |
authxi.login |
Redirects to authxi. returnTo must be a path on this site; anything else is ignored. |
GET /auth/callback |
authxi.callback |
Checks the response, finds or creates the user, signs them in to the guard and redirects to the intended page. |
GET or POST /auth/logout |
authxi.logout |
Signs out of the guard, invalidates the session and ends the authxi session (with id_token_hint). Prefer POST with @csrf. |
Change the prefix or middleware in config/authxi.php (routes), or turn the routes off with AUTHXI_ROUTES=false
and use Authxi::provider() in your own controller.
After sign-in the ID token and its claims are in the session: Authxi::claims(), Authxi::idToken().
Where users land
The page to return to is Laravel's intended URL. Authxi::login('/billing') and ?returnTo= set it, and Laravel's
auth middleware sets it when it turns a guest away. Before redirecting, the callback keeps it only if it is a path on
this site (or an absolute URL on this site's origin, which becomes its path). //host, /\host, other origins and
control characters are dropped, so the callback can't be used as an open redirect. With no intended page, users go to
authxi.home (default /).
Authxi::login($returnTo) throws an AuthxiException with code invalid_return_to for an unsafe value.
Authxi::safeReturnTo($value) returns the path or null.
Step-up (two-step verification)
Before a sensitive action, ask for a fresh check:
use Authxi\Laravel\Facades\Authxi; if (! Authxi::verifiedWithin(300)) { // The user sees "To continue: Pay invoice INV-1042" on authxi, then comes back here. return Authxi::stepUp(reason: 'Pay invoice INV-1042', returnTo: '/billing?pay=INV-1042', maxAge: 300); }
stepUp()sendsacr_values=mfa.reasonis shown on the check (cut at 120 characters). WithmaxAge, a check passed within that many seconds is accepted without asking again.verifiedWithin($seconds)readsmfa_timefrom the claims stored at sign-in.- If the user cancels or fails the check, they stay signed in and the callback reports the error like any other.
- If authxi returns without a check made after the request (or within
maxAge), the callback refuses it withstep_up_failed.
Middleware
Route::get('/payouts', ...)->middleware(['auth', 'authxi.verified:300']); Route::get('/payouts/account', ...)->middleware(['auth', 'authxi.verified:300,Change payout account']);
authxi.verified:{seconds},{reason} passes when the last check is at most seconds old. Otherwise a GET goes through
step-up and back to the same URL; any other method goes back to the previous page, since a form post can't be
replayed. JSON requests get 403 {"error": "verification_required"}.
Users
By default the callback runs Authxi\Laravel\UserResolver:
- Find the user whose
authxi_idis the token'ssub(stable per workspace). - Otherwise, if authxi verified the email, link the user with that email and no
authxi_idyet. - Otherwise create one (with a random password, for the
passwordcolumn of Laravel's default users table).
Name and email are updated from authxi on every sign-in. If the email belongs to another account, the sign-in fails
with user_conflict. The model is the guard's provider model (authxi.user_model to change it) and the column is
authxi.user_id_column.
To decide yourself, register a resolver, for example in AppServiceProvider::boot():
use Authxi\Laravel\AuthxiUser; use Authxi\Laravel\Facades\Authxi; Authxi::resolveUsersUsing(function (AuthxiUser $authxi) { if ($authxi->hostedDomain() !== 'acme.com') { return null; // refuses the sign-in with access_denied } return User::updateOrCreate(['authxi_id' => $authxi->getId()], [ 'email' => $authxi->getEmail(), 'name' => $authxi->getName(), 'avatar' => $authxi->getAvatar(), ]); });
Or set authxi.user_resolver to an invokable class.
Authxi\Laravel\AuthxiUser has getId() (the sub), getEmail(), getName(), getAvatar() (the picture),
getRaw() (every claim) and the public properties id, name, email, avatar, token, expiresIn and
approvedScopes. It adds getIdToken(), claims(), claim($name), emailVerified(), hostedDomain() (hd),
amr(), acr(), mfaTime(), verifiedWithin($seconds), authTime(), sessionId() (sid) and appMetadata().
Errors
A failed sign-in is an Authxi\Laravel\AuthxiException:
$e->error: an OAuth code from authxi (access_denied,login_required,invalid_grant, ...) or a check made here:state_mismatch,issuer_mismatch,invalid_token,discovery_failed,token_exchange_failed,invalid_return_to,not_a_callback,step_up_failed,user_conflict,invalid_config.$e->description: authxi'serror_description, written for the user: not invited, domain not allowed, waiting for approval, blocked, 2FA failed.$e->userMessage(): the description, or a short safe message for the package's own checks.$e->getMessage(): details for your logs.
The built-in callback redirects to authxi.error_redirect (a path or route name, default /) with
session('authxi_error') (the message to show) and session('authxi_error_code').
Your own controller
use Authxi\Laravel\AuthxiException; use Authxi\Laravel\Facades\Authxi; public function redirect() { return Authxi::provider()->redirect(); // or ->stepUp('Change payout account', maxAge: 300)->redirect(), ->prompt('select_account'), ->loginHint($email) } public function callback() { try { $authxi = Authxi::provider()->user(); } catch (AuthxiException $e) { return redirect('/')->with('error', $e->userMessage()); } Auth::login(Authxi::resolveUser($authxi)); Authxi::storeSession($authxi); // for verifiedWithin() and logoutUrl() return redirect()->intended('/'); }
Authxi::provider() returns an Authxi\Laravel\AuthxiProvider set up from the config. Besides redirect() and
user() it has with([...]) for extra /authorize parameters (state, nonce and the PKCE challenge can't be
replaced), scopes([...]), setScopes([...]), redirectUrl($url) and userFromToken($accessToken) (reads
/userinfo). It keeps its transaction (state, nonce, PKCE verifier) in the session, so it has no stateless() mode.
Authxi::logoutUrl() returns the authxi logout URL with id_token_hint; read it before invalidating the session.
To check an ID token a single-page app sent to your API: Authxi::verifyIdToken($token) returns the claims or
throws invalid_token.
What is checked
- Discovery comes from
{issuer}/.well-known/openid-configuration, cached for an hour, and must name the same issuer. Signing keys are cached for 10 minutes; a token with an unknownkidrefreshes them (at most once per 10 seconds). - ID tokens must be RS256 (
noneandHS*are refused) and signed by a key in the JWKS.issmust be the issuer,audmust contain the client id,expandiatare checked with 60 seconds of leeway, andnoncemust match the one sent. - The callback's
statemust match the transaction in the session, which is single use and expires after 10 minutes. Itsissparameter must be the issuer (RFC 9207 mix-up defence); authxi always sends it. - The client secret goes in a
client_secret_basicheader (client_secret_postwithAUTHXI_TOKEN_AUTH_METHOD=client_secret_post). Without a secret, only the client id and PKCE are sent.
Testing your app
To test pages behind sign-in, skip authxi and act as a user. Add claims when a route uses authxi.verified:
$this->actingAs($user) ->withSession(['authxi' => ['id_token' => 'test', 'claims' => ['sub' => 'usr_1', 'mfa_time' => time()]]]) ->post('/payouts') ->assertOk();
To test the sign-in itself, fake authxi with Http::fake(): serve discovery, a JWKS with a public key you generated,
and a /token response with an ID token you signed with firebase/php-jwt (use the nonce from the /auth/login
redirect). This package's own suite does that in tests/Support/FakeAuthxi.php, a working example.
Call Http::preventStrayRequests() so no test reaches a real issuer. Discovery and keys are cached in the default
cache store; use the array store in tests, or point authxi.cache_store at one.
Upgrading from 0.1
0.2 no longer depends on laravel/socialite. The two classes moved out of the Socialite namespace, and there is no
authxi Socialite driver any more:
| 0.1 | 0.2 |
|---|---|
Authxi\Laravel\Socialite\AuthxiUser |
Authxi\Laravel\AuthxiUser |
Authxi\Laravel\Socialite\AuthxiProvider |
Authxi\Laravel\AuthxiProvider |
Socialite::driver('authxi') |
Authxi::provider() (Authxi\Laravel\Facades\Authxi) |
composer require authxi/laravel:^0.2- Replace the names above in your code and tests. The methods are the same:
redirect(),user(),stepUp(),prompt(),loginHint(),with(), and on the usergetId(),getEmail(),getName(),getAvatar(),getRaw(),setRaw(),map(),getIdToken()and the authxi claims. - If your composer.json requires
laravel/socialiteonly for authxi,composer remove laravel/socialite.
The routes, the Authxi facade, the authxi.verified middleware, the config and the session keys are unchanged.
The user no longer implements Socialite's User contract or ArrayAccess: read claims with claim('hd') or
getRaw()['hd'] instead of $user['hd'].
Development
composer install vendor/bin/phpunit # uses a fake issuer AUTHXI_LIVE_ISSUER=http://demo.localhost:8180 vendor/bin/phpunit --testsuite live # against a local authxi backend