Authentication
Publish the sign-in, password reset, email verification and profile pages, add two-factor sign-in, send guests to them, and rely on the logout route and signed-in user the package provides.
Every panel page runs behind auth:{guard}, except pages that replace their middleware to stay public, such as the auth pages below. The package handles the parts that only make sense inside a panel:
- Sign-out. Every panel answers
POST {prefix}/logout, which the user menu posts to. - The signed-in user. The panel's guard user is shared as the
tbtop.userInertia prop, which the header's user menu reads. - Sign-in, password reset, email verification and the profile page. These ship as base pages.
admin:install --authpublishes them into your app, where you own them. - Two-factor sign-in.
admin:install --2faadds a TOTP challenge with recovery codes and a two-factor section on the profile page.
The host app still owns the rest of authentication: the user model, the guard, the password broker, and anything beyond the pages above. Registration does not ship. See What stays yours.
Publish the auth pages
php artisan admin:install --authThis writes five files to app/Admin/Pages/Auth/:
| File | Path | Route name |
|---|---|---|
LoginPage.php | {prefix}/login | tbtop.{panel}.login-page |
ForgotPasswordPage.php | {prefix}/forgot-password | tbtop.{panel}.forgot-password-page |
ResetPasswordPage.php | {prefix}/reset-password/{token} | tbtop.{panel}.reset-password-page |
ProfilePage.php | {prefix}/profile | tbtop.{panel}.profile-page |
EmailVerificationPage.php | {prefix}/verify-email | tbtop.{panel}.email-verification-page |
Each file is an empty subclass of a package base page in Tbtop\Admin\Auth:
<?php
namespace App\Admin\Pages\Auth;
class LoginPage extends \Tbtop\Admin\Auth\LoginPage {}The behaviour lives in the base, so fixes arrive with composer update. The file is yours: override a hook in it to change the screen, or delete it to drop the screen. Deleting ForgotPasswordPage and ResetPasswordPage drops password reset, and the login page stops showing its "Forgot your password?" link. Deleting ProfilePage drops the profile page and its entry in the user menu. Deleting EmailVerificationPage drops the verification check.
How the command behaves:
- One panel per run. With several panels registered, pass
--panel=<id>. With none registered, or several and no--panel, it refuses and changes nothing. - It never overwrites. A file that already exists is reported and left alone, unless you pass
--force. - It skips pages the panel already serves. If the panel already has a page at the same path or slug, such as a login page you wrote earlier, that page is skipped. Two would break every request to the panel with a duplicate-slug error. Delete your old page first if you want the published one.
- It prints the steps it does not do for you. The guest redirect below, and a
discoverPages()line when the panel does not discoverapp/Admin/Pages.
If your app signs users in through its own screens and you only want the profile page, run php artisan admin:install --profile instead. It publishes ProfilePage.php alone and behaves the same way: one panel per run, no overwrites without --force.
Without --auth or --profile, admin:install publishes only the root view, the JS entry and the stylesheet, as before.
Each panel gets its own directory. The first panel uses app/Admin/Pages/Auth. For a second panel, --auth --panel=<id> writes to Auth/ under that panel's first discoverPages() root, or else to app/Admin/{Id}/Pages/Auth (ops-admin becomes OpsAdmin) and prints a discoverPages() hint. If another panel still owns the target directory, the command refuses and writes nothing.
Send guests to the login page
When a guest opens a protected page, Laravel's auth middleware redirects to the route named login. Without such a route, the guest gets a 500. Point the redirect at the panel's login page:
->withMiddleware(function (Middleware $middleware): void {
$middleware->redirectGuestsTo(fn () => \Tbtop\Admin\Auth\LoginPage::currentUrl() ?? '/admin/login');
})LoginPage::currentUrl() returns the login page of the panel the request belongs to, so one line serves every panel. Outside a panel it returns null, and the fallback applies. '/admin/login' suits an app where only the panel needs sign-in; use your panel's prefix if it is not admin. If your public site has its own login route, return it as the fallback instead, so site guests keep landing there:
$middleware->redirectGuestsTo(fn () => \Tbtop\Admin\Auth\LoginPage::currentUrl() ?? route('login'));What the pages do
The sign-in and password reset pages share one shell:
- Public. Their middleware is
['web', RedirectSignedInUsers::class], not the panel's stack. A guest can reach them even when the panel's stack carries an access check. - Signed-in users are sent into the panel. A user already signed in on the panel's guard who opens one of them lands on the panel root. Laravel's own
guestmiddleware is not used, because it redirects to the app's home route, which knows nothing about panels. - Never the panel home. The panel root redirect skips auth pages, whatever order they are registered in.
- Hidden from MCP. Signing in needs a browser session.
- Chrome-less. They use the
centerlayout, and their forms skip the unsaved-changes guard.
Sign-in checks email and password on the panel's guard, never the app's default guard. It has a "Remember me" checkbox. Failed attempts are throttled to five a minute per email and IP address. When the throttle trips it fires Laravel's Illuminate\Auth\Events\Lockout event, so a listener you already have for Breeze or Fortify lockouts keeps working. On success it renews the session and sends the user to the page they were bounced from, or to the panel root.
Forgot password emails a reset link that opens the panel's reset page, not Laravel's password.reset route. Laravel's global ResetPassword::createUrlUsing() is left alone for your app's own links. The answer is the same whether or not the email is registered, so the form does not reveal which accounts exist. Requests are throttled to five a minute per IP address.
Reset password sets the new password, rotates the remember token so other devices with a remember cookie are signed out, and sends the user to the login page. An unknown email gets the same answer as a bad token, and failed attempts are throttled to five a minute per IP address.
All three forms answer malformed input, such as an array where a string belongs, with an ordinary validation error rather than a server error. The throttle messages say what was throttled: sign-in attempts, reset link requests or reset attempts.
The pages assume a user model with email and password columns, and the password_reset_tokens table from Laravel's application skeleton.
Customize the pages
Override a hook in the published subclass. The login page has the most:
| Hook | What it controls |
|---|---|
view(S $s) | The whole screen. |
credentials(ActionCtx $ctx) | The array the guard's provider matches the user by, plus password. Defaults to email and password. |
afterAuthenticated(Authenticatable $user, ActionCtx $ctx) | Runs after the session is established. Return a URL to send the user there instead of redirectTo(). Return null to carry on. |
redirectTo(ActionCtx $ctx) | Where the user lands: the intended URL, else the panel root. |
throttleKey(ActionCtx $ctx) | The rate-limit key. Defaults to the login value from credentials() plus the IP address. |
maxAttempts() | Failed attempts allowed per key per minute. Defaults to 5. |
static middleware(PanelConfig $panel) | The page's middleware. Extend it to add an allowlist, since the page skips the panel's stack. |
ResetPasswordPage adds passwordRules(), which defaults to ['required', 'confirmed', Password::defaults()]. ForgotPasswordPage has only view().
Let only active accounts sign in. Every key besides password becomes a condition on the user query:
use Tbtop\Admin\Actions\ActionCtx;
class LoginPage extends \Tbtop\Admin\Auth\LoginPage
{
protected function credentials(ActionCtx $ctx): array
{
return [...parent::credentials($ctx), 'is_active' => true];
}
}The throttle key uses the first value in credentials() other than password, so keep the login field first. To sign in by something other than email, also rebuild view() (see Rebuild the screen): the default form's field is named email and validated as an email address.
Run code after sign-in
afterAuthenticated() runs once the user is signed in, and a URL it returns is where the login sends them. With two-factor sign-in on, it runs for a user with a factor only after the code passes, and its URL wins over the challenge page's own redirectTo().
Rebuild the screen
The security cores are protected methods: authenticate() on the login page, sendLink() on forgot password, resetPassword() on reset. A subclass that rebuilds view() calls them from its form's onSubmit, so throttling and session renewal stay in place:
use Tbtop\Admin\Actions\ActionCtx;
use Tbtop\Admin\Dsl\Node;
use Tbtop\Admin\Dsl\S;
public function view(S $s): Node
{
return $s->stack([
$s->displayText('Staff sign-in')->variant('heading'),
$s->form('login', [
$s->text('email')->label('Work email')->required()->rules('email'),
$s->password('password')->label('Password')->required(),
$s->actionsRow([
$s->action('submit')->label('Sign in')->color('primary')->submit(),
]),
])
->guardUnsaved(false)
->record(['email' => '', 'password' => ''])
->onSubmit(fn (ActionCtx $ctx): string => $this->authenticate($ctx)),
]);
}To change what a core does, override it and wrap parent::authenticate($ctx) rather than copying it.
The pages' text comes from the auth.login, auth.forgot and auth.reset keys of the package's translation file. See Interface text to override them.
The profile page
ProfilePage lets the signed-in user change their own name, email and password. Unlike the sign-in pages it is not public: it runs behind the panel's auth stack and edits the user of the panel's guard.
- Two forms. The first holds name and email. A new email needs the current password, so a hijacked session cannot point password resets at another inbox. The second changes the password and also asks for the current one.
- Throttled. Wrong current passwords are limited to five a minute per user, counted across both forms.
- Other sessions are signed out. A password change keeps the current session and signs out every other one, including remember-me cookies on other devices.
- A user menu entry. While the panel serves a
ProfilePagesubclass, the user menu starts with a "Profile" item that links to it. You no longer need auserMenuItems()link of your own; remove it if you added one, or the menu shows two. - Hidden from MCP, like the other auth pages.
Its hooks:
| Hook | What it controls |
|---|---|
view(S $s) | The whole screen. Call parent::view($s) and stack your own sections after it, such as a two-factor setup card. |
profileForm(S $s) | The name and email form. |
passwordForm(S $s) | The password form. |
profileRules(Model $user) | Rules for name and email. By default a new email must be lowercase and unique among users, on the user model's own connection and table. |
passwordRules() | Rules for the new password. Defaults to ['required', 'string', 'confirmed', Password::defaults()]. |
Add a phone number to the profile rules:
use Illuminate\Database\Eloquent\Model;
class ProfilePage extends \Tbtop\Admin\Auth\ProfilePage
{
protected function profileRules(Model $user): array
{
return [...parent::profileRules($user), 'phone' => ['nullable', 'string', 'max:32']];
}
}A new rule only validates and saves the field; override profileForm() as well to show an input for it.
The page needs an Eloquent user model with name, email and password attributes. When the model implements MustVerifyEmail, a changed email is marked unverified and, while the panel serves an EmailVerificationPage, a link is mailed to the new address.
Email verification
EmailVerificationPage is opt-in twice: the panel serves the published subclass, and the user model implements Laravel's MustVerifyEmail, with an email_verified_at column. Then an unverified user is sent from every panel page to {prefix}/verify-email, and a JSON request gets a 403. The page itself, the profile page (to fix a mistyped address) and logout stay open.
- The page. It has no panel chrome: a button mails the link, limited to six a minute per user (
maxAttempts()), plus links to the profile and sign-out. - The link. A temporary signed URL, valid for
auth.verification.expireminutes (60 by default), sent asVerifyEmailNotification. Opening it marks the user verified, fires Laravel'sVerifiedevent and returns them to the page they were sent away from. A bad signature, another user's link or a link for an old address answers 403. Laravel'sVerifyEmail::createUrlUsing()and the skeleton'sverification.*routes stay yours and are not used. - Nothing is mailed at sign-in. A user an admin created asks for the link from the page. To send one from your own code, such as after a registration you wrote:
EmailVerificationPage::sendVerificationLink($user). It returnsfalsewhen the current panel serves no subclass.
The check is RequireVerifiedEmail, the last middleware of authStack(). Delete the page and the check goes with it.
Two-factor sign-in
composer require pragmarx/google2fa bacon/bacon-qr-code
php artisan admin:install --2fa
php artisan migrate--2fa publishes the auth pages plus TwoFactorChallengePage ({prefix}/two-factor-challenge) and a migration for the user table. The columns are Fortify's (two_factor_secret, two_factor_recovery_codes, two_factor_confirmed_at) plus two_factor_last_used_step. The migration adds only the missing ones, so users who enrolled through Fortify keep their factor. Add the two secret columns to the user model's $hidden, and give them no cast: the package encrypts them itself.
While the panel serves the challenge page:
- The profile page shows a "Two-factor authentication" section. The user turns it on with their current password, scans the QR code and confirms with the first code. Eight recovery codes are shown once. New codes and turning it off both take a code.
- The login checks the password but does not sign in a user who has a factor. It parks them for the challenge, which takes a TOTP or a recovery code, five tries a minute before the password is asked again. A parked sign-in lasts ten minutes and ends if the password changes. The "remember me" choice carries over.
RequireTwoFactorinauthStack()sends any session that has not passed the challenge, such as one a remember cookie restored, to the challenge page, and answers a JSON request with 403. Logout stays open, and a page whose ownmiddleware()leaves outauthStack()opts out.
The pass belongs to the user who earned it in this session. Delete TwoFactorChallengePage to turn it all off.
Choose the password broker
Reset uses the app's default password broker. A panel whose guard reads users from a different provider, such as an admins table, needs its own broker in config/auth.php. Name it on the panel:
$panel->guard('admin')->passwordBroker('admins');null, the default, uses the app's default broker.
Sign out
The user menu's "Logout" item posts to {prefix}/logout, which is /admin/logout for a panel mounted at admin. The package registers this route on every panel, named tbtop.{panel}.logout. It signs out the panel's guard, invalidates the session, and redirects to the panel root, where the guest redirect takes the user to the login page.
If the session has already expired, the logout request fails the CSRF check with a 419. The panel answers that with the same redirect, instead of Inertia's error modal.
Remove your own logout route
Older versions of these docs had you register POST admin/logout yourself. Delete that route when you upgrade. The package route now handles it on the panel's guard.
The signed-in user
The package shares the panel guard's user as the tbtop.user prop: the model serialized with toArray(), or null for a guest. Panels with different guards each see their own user. The user menu shows name, and falls back to the part of email before the @.
The model's serialization is the only filter
Whatever the model's toArray() returns reaches every page's HTML. The package removes nothing on top of it, so list sensitive attributes in $hidden (or limit the model with $visible).
The client reads the user only from tbtop.user. An auth.user prop shared from your own Inertia middleware is no longer read, so you can remove it if nothing else in your app uses it. A custom component that reads the user gets AuthUser, typed as { id: string | number; email: string; name?: string } plus any other serialized attributes. The type assumes email is serialized, so keep it out of $hidden.
What stays yours
- Registration and passkeys. Neither ships. Write registration as a public DSL page, and call
EmailVerificationPage::sendVerificationLink($user)after it creates the user. - Access control. Signing in proves who the user is, not that they belong in the admin. Limit the panel to staff with access control.
- An existing login screen. If you keep a React login screen in your app's own Inertia bundle, such as a Breeze screen, skip
--authand end its sign-in with a full page load into the panel: returnInertia::location('/admin')from the controller. A plainredirect()is followed inside your app's bundle, which cannot render admin pages. The logout route and the shared user work either way.
See it in the demo
The live demo runs on the published pages: demo.tbtop.dev/admin/login.
Next steps
- Write your first page.
- Register a panel: limit the panel to staff.
Customize the panel
Change the admin's style preset, colours, fonts, dark mode, layout, header, sidebar, logo, favicon and interface text, and know which host file each change lives in.
Your first page
Build a list, a create form and an edit form for a Post model, from the make:tbtop-page scaffold to a working save.