# Upgrading From Fortify

Source: https://keyringauth.com/docs/0.x/upgrading-from-fortify

## Introduction

Keyring covers what Fortify does: login, registration, password resets, email verification, password confirmation and two-factor authentication. It takes Fortify's place in your app.

Fortify keeps two-factor state in three columns on the `users` table, so a user gets one authenticator app. Keyring stores each sign-in method in its own table, so a user can have several.

Your users keep their passwords, authenticator apps, recovery codes and `laravel/passkeys` passkeys. Two things change:

- Bcrypt only stores the first 72 bytes of a password. Keyring refuses longer input rather than compare a truncated value, so users with a password over 72 bytes on a bcrypt hash must reset it.
- Keyring [checks passwords in Unicode's NFC form](https://keyringauth.com/docs/0.x/protected-changes#password-rules). A password typed with a letter and a separate accent, rather than the accented letter, won't match its old hash.

## Steps

1. Install Keyring and publish its files, keeping Fortify for now:

   ```bash
   composer require keyring/keyring
   php artisan keyring:install
   php artisan migrate
   ```

   Choose the sign-in methods your users already have: the authenticator app for Fortify's two factor, and passkeys for `laravel/passkeys`. Turn on any Fortify feature you used, such as password resets. Keyring won't sign in a user with authenticators for a method it doesn't have, and `keyring:import` won't import into one.

2. Add the `Keyring\Concerns\HasKeyring` trait to your user model. You may keep Fortify's `TwoFactorAuthenticatable` trait until the import is done.

3. Import your two-factor data and passkeys. Run a dry run first:

   ```bash
   php artisan keyring:import fortify --dry-run
   php artisan keyring:import fortify
   ```

   The command exits non-zero if any factor couldn't be imported. Fix those before you go on. See [Importing Two-Factor Data](https://keyringauth.com/docs/0.x/upgrading-from-fortify#importing-two-factor-data).

4. Remove `laravel/fortify`, its provider (`App\Providers\FortifyServiceProvider`, in `bootstrap/providers.php`), `config/fortify.php`, and any Fortify actions you no longer need. Keyring uses several of Fortify's route names, such as `login`, `register` and `password.request`, so both can't stay installed.

5. Move your settings into `config/keyring.php` and `app/Providers/KeyringServiceProvider.php`, using the tables below.

6. Update your frontend for the [challenge page](https://keyringauth.com/docs/0.x/sign-in-flow#the-challenge-page) and the [authenticator routes](https://keyringauth.com/docs/0.x/authenticators).

7. Once everything works, drop Fortify's columns in a migration of your own:

   ```php
   Schema::table('users', function (Blueprint $table) {
       $table->dropColumn(['two_factor_secret', 'two_factor_recovery_codes', 'two_factor_confirmed_at']);
   });
   ```

## Replacing Fortify in a Starter Kit

Laravel's starter kits come with Fortify wired in. A new app from a kit is still an upgrade, just one with no users to import. Follow the [steps](https://keyringauth.com/docs/0.x/upgrading-from-fortify#steps) and skip the import. The tables are a checklist, based on the React starter kit that the [example application](https://github.com/keyringauth/example) started from. Other kits differ in places.

**Remove**

| File | Why |
|---|---|
| `app/Providers/FortifyServiceProvider.php`, and its line in `bootstrap/providers.php` | `keyring:install` adds `KeyringServiceProvider`. |
| `config/fortify.php` | `config/keyring.php` replaces it. |
| `app/Actions/Fortify/` and `app/Concerns/PasswordValidationRules.php` | The published `app/Actions/Keyring/` actions replace them. |
| `app/Http/Requests/Settings/PasswordUpdateRequest.php` and `app/Http/Requests/Settings/TwoFactorAuthenticationRequest.php` | Keyring's routes validate these requests. |
| `app/Http/Requests/Settings/ProfileDeleteRequest.php` | It asks for the current password. The `keyring.fresh` middleware on the route asks for more. |
| The `add_two_factor_columns_to_users_table` and `create_passkeys_table` migrations | Only in an app with no users. Otherwise keep them until the import is done. |
| The two-factor and passkey components, and the `auth/two-factor-challenge` and `auth/confirm-password` pages | Your `challenge` and `confirm` pages, and your settings page, replace them. |

**Change**

| File | What |
|---|---|
| `app/Models/User.php` | Swap `TwoFactorAuthenticatable`, `PasskeyAuthenticatable` and the `PasskeyUser` interface for `HasKeyring`. Remove the `two_factor_*` attributes from the hidden list and the casts. |
| `database/factories/UserFactory.php` | Remove the `two_factor_*` attributes and `withTwoFactor()`. Tests use [Keyring's factories](https://keyringauth.com/docs/0.x/testing#factories). |
| `routes/settings.php` | Remove `PUT settings/password`. Keyring's `PUT /user/password` route has the same name, `user-password.update`. Replace the `RequirePassword` middleware on the security page with `keyring.fresh:15m`, and put the same middleware on the delete account route. |
| The profile controller | With `Features::emailChanges()` on, save only the name. The email goes through [`POST /user/email`](https://keyringauth.com/docs/0.x/protected-changes#changing-the-email-address). |
| The security settings controller | Pass everything [Your Settings Page](https://keyringauth.com/docs/0.x/quick-start#your-settings-page) lists. Its password form posts to Keyring's route. |
| `app/Http/Middleware/HandleInertiaRequests.php` | Share `status` and `keyring.alerts`. See [Flash Messages and Alerts](https://keyringauth.com/docs/0.x/frontend#flash-messages-and-alerts). |
| `auth/login` | Keep the passkey button, and point its `@laravel/passkeys` hook at [Keyring's two login routes](https://keyringauth.com/docs/0.x/passkeys#laravels-passkeys-client). Or use [`usePasskeyLogin()`](https://keyringauth.com/docs/0.x/frontend#signing-in-with-a-passkey). |
| `auth/register` and `auth/reset-password` | No longer receive a `passwordRules` prop, so make it optional or remove it. |
| The kit's auth tests | They assert Fortify's routes and columns. Rewrite them. See [Testing](https://keyringauth.com/docs/0.x/testing). |

The kit's pages already use the names Keyring renders. For step-up, add an `auth/confirm` page, or reuse the challenge page:

```php
Keyring::page('confirm', 'auth/challenge');
```

## Importing Two-Factor Data

`php artisan keyring:import fortify` copies three kinds of data:

- each user's `two_factor_secret` into a `totp` authenticator named "Authenticator app", which becomes their default,
- their `two_factor_recovery_codes` into a `recovery` authenticator, stored as a hash,
- each `laravel/passkeys` row into a `passkey` authenticator, keeping its name, credential, counter and last-used time.

Before you run it:

- **Keys.** The command decrypts with Fortify's encrypter, the one set with `Fortify::encryptUsing()`. Without one, it uses Eloquent's encrypter and `APP_KEY`. It has to be the key Fortify used.
- **Confirmation.** A user has two factor when Fortify would challenge them. With Fortify's `confirm` option on, that means `two_factor_confirmed_at` is set. The command reads the option from `config/fortify.php`. If it can't tell, rows without a confirmed date fail until you pass `--fortify-confirm=on` or `--fortify-confirm=off`.
- **Skipped rows.** Unconfirmed secrets are skipped, since Fortify wasn't enforcing them. Pass `--unconfirmed` to import them anyway.
- **Reporting.** Each row is imported, already imported, skipped or failed. Skipped and failed rows are listed with the user ID and reason. That includes users hidden by global scopes, such as soft-deleted users.
- **Failures.** The command exits non-zero when anything fails: a secret or codes it can't decrypt, a passkey with no user, a credential ID that isn't base64url, or a credential that isn't a WebAuthn record. A user whose two-factor data failed gets a placeholder authenticator app that can't be verified, so they're still challenged rather than signing in with only a password. The usual cause is the wrong key. Fix it and run the command again, and the correct data replaces the placeholder. If the data is gone, delete the placeholder with `Authenticator::where('meta->import_failed_from', 'fortify')`, and the user enrolls again. A failed passkey has no placeholder, so the user adds it again.
- **Existing methods.** The command only imports into users with no sign-in methods in Keyring. Once a user has some, those are theirs, so a later run never brings back a method they removed.
- **Re-running.** It's safe to run more than once. It never changes Fortify's columns or the `passkeys` table. Drop them once the import is clean.
- **Factors.** Imported passkeys need `WebAuthn::passkeys()` in your [factors](https://keyringauth.com/docs/0.x/factors). Imported codes need `Totp` and `RecoveryCodes`.
- **RS256.** `laravel/passkeys` accepts RS256 keys, but Keyring doesn't by default. A Windows Hello passkey may import and then be refused at sign-in. The command still imports it, since it may be the user's only method, and the passkey works once the application accepts its algorithm. The command warns how many passkeys will be refused, and whose. Add `RS256` to [`webauthn.algorithms`](https://keyringauth.com/docs/0.x/passkeys#rs256-and-windows-hello) to keep them working, or those users need a new passkey. An RSA key shorter than `webauthn.minimum_rsa_bits` gets the same warning. Warnings don't change the exit code.
- **Frozen accounts.** An imported app and its codes count as added when Fortify's `two_factor_confirmed_at` says so, and a passkey when its row was made. With Fortify's `confirm` option off there's no confirmed date, so they count as added at the import. Those accounts are [frozen](https://keyringauth.com/docs/0.x/authenticators#frozen-sign-in-methods) for 7 days: they can't remove, rename or replace the app or codes until then, unless they prove an [established](https://keyringauth.com/docs/0.x/authenticators#established-authenticators) passkey.
- **Recovery codes.** They work as before. Type them as Fortify showed them, capitals included. Spaces and dashes are ignored. Keyring stores each code as a keyed hash. OWASP ASVS 5.0.0 requirement 6.5.2 allows that for codes with 112 random bits or more. Fortify's 20 letters and digits have 119 bits, but only while their case counts, so an imported code must be typed exactly as shown. Codes Keyring generates are case-insensitive. A set holding anything other than Fortify's own format is skipped, and those users generate new codes.
- **Dry run.** `--dry-run` reports the same outcome and exit code, and writes nothing.

## How Fortify Concepts Map

### Configuration

| Fortify | Keyring |
|---|---|
| `fortify.guard` | `keyring.guard` |
| `fortify.username` | `keyring.username` |
| `fortify.lowercase_usernames` | Always on. Keyring lowercases input, so store addresses in lowercase. If you turned this option off, lowercase existing addresses before switching, or those users can't sign in. |
| `fortify.home` | `keyring.home` |
| `fortify.prefix`, `fortify.domain`, `fortify.middleware` | `keyring.prefix`, `keyring.domain`, `keyring.middleware` |
| `fortify.passwords` | `keyring.passwords.broker` |
| `fortify.views` | Always on. Use `Keyring::page()` to change a page. |
| `fortify.limiters` | `keyring.limits`, a factor's `limits()` method, and the `keyring` rate limiter for form routes. See [Rate Limiting](https://keyringauth.com/docs/0.x/upgrading-from-fortify#rate-limiting). |
| `Features::registration()` | `Keyring\Features::registration()` |
| `Features::resetPasswords()` | `Keyring\Features::resetPasswords()` |
| `Features::emailVerification()` | `Keyring\Features::emailVerification()` |
| `Features::updatePasswords()` | `Keyring\Features::updatePasswords()`, which also [protects](https://keyringauth.com/docs/0.x/protected-changes#protected-attributes) the password. |
| `Features::updateProfileInformation()` | Not included. Keep your own profile route. With `Keyring\Features::emailChanges()`, leave `email` out of it. |
| `Features::twoFactorAuthentication()` | Register `Totp` and `RecoveryCodes` in `Keyring::factors()`, turn on `Keyring\Features::manageAuthenticators()`, and choose a [policy](https://keyringauth.com/docs/0.x/policies). |

### Actions

| Fortify | Keyring |
|---|---|
| `Fortify::createUsersUsing(CreateNewUser::class)` | `Keyring::createUsersUsing(CreateNewUser::class)`, with an action implementing `Keyring\Contracts\CreatesNewUsers`. Split `create()` in two: validation goes in `validate()`, without the `unique` rule on the address, since Keyring checks that. The rest stays in `create()`, which receives what `validate()` returned. |
| `Fortify::resetUserPasswordsUsing()` | `Keyring::resetUserPasswordsUsing()`, with an action implementing `Keyring\Contracts\ResetsUserPasswords`. Keep the `reset()` body, and type the user as `Authenticatable&Model $user` with a `@param User $user` docblock. |
| `Fortify::updateUserPasswordsUsing()` | `Keyring::updateUserPasswordsUsing()`, with an action implementing `Keyring\Contracts\UpdatesUserPasswords`. Keep the body and change the signature. Keyring checks `current_password` before your action runs, so drop your own check. |
| `PasswordValidationRules` trait | The published `PasswordValidationRules` trait, built on [Keyring's rules](https://keyringauth.com/docs/0.x/protected-changes#password-rules). |
| `Fortify::updateUserProfileInformationUsing()` | Your own code. Email changes go through [Keyring's flow](https://keyringauth.com/docs/0.x/protected-changes#changing-the-email-address), since `email` is protected. Your `ValidateEmailChange` action holds their validation. |
| `Fortify::authenticateUsing()` | `Keyring::findUsersUsing()` finds the user. Keyring checks the password itself. See [Finding the User](https://keyringauth.com/docs/0.x/sign-in-flow#finding-the-user). |
| `Fortify::confirmPasswordsUsing()` | Not needed. Step-up accepts any qualifying factor. |

### Views and Pages

| Fortify | Keyring page |
|---|---|
| `Fortify::loginView()` | `login` |
| `Fortify::registerView()` | `register` |
| `Fortify::requestPasswordResetLinkView()` | `forgot-password` |
| `Fortify::resetPasswordView()` | `reset-password` |
| `Fortify::verifyEmailView()` | `verify-email` |
| None. Fortify's link verifies the address when it's opened. | `email-verification`, the page the link opens |
| `Fortify::twoFactorChallengeView()` | `challenge` |
| `Fortify::confirmPasswordView()` | `confirm` |

Pass a component name or a closure to `Keyring::page()`. See [Pages](https://keyringauth.com/docs/0.x/sign-in-flow#pages).

### Routes

| Fortify | Keyring |
|---|---|
| `POST /two-factor-challenge` | `POST /login/challenge/{factor}` |
| `POST /user/two-factor-authentication` | `POST /user/authenticators/totp`, with `password` while the account has no [established](https://keyringauth.com/docs/0.x/authenticators#the-password-for-a-first-second-factor) second factor. |
| `POST /user/confirmed-two-factor-authentication` | `POST /user/authenticators/totp/confirm` |
| `DELETE /user/two-factor-authentication` | `DELETE /user/authenticators/{id}` |
| `GET /user/two-factor-qr-code`, `GET /user/two-factor-secret-key` | Returned by `POST /user/authenticators/totp` (`qr`, `secret`, `url`). |
| `GET /user/two-factor-recovery-codes` | Not available. Codes are stored as hashes and shown only when created. |
| `POST /user/two-factor-recovery-codes` | `POST /user/authenticators/recovery`, then `.../recovery/confirm`. |
| `GET` and `POST /user/confirm-password` | `GET /confirm` and `POST /confirm/{factor}` |
| `PUT /user/password` | `PUT /user/password` (same name, `user-password.update`) |
| `PUT /user/profile-information` | Not included. |

Fortify's `password.confirm` middleware keeps working, since confirming through Keyring satisfies it, as long as the confirm proved something recently. A round trip to a provider whose sign-ins are [never fresh](https://keyringauth.com/docs/0.x/sso#freshness) doesn't count. Keyring's [`keyring.fresh`](https://keyringauth.com/docs/0.x/step-up#fresh-verification) middleware is stricter: a user with a second factor must confirm with it, not with the password alone. See [Laravel's Password Confirmation](https://keyringauth.com/docs/0.x/step-up#laravels-password-confirmation).

### Responses

Swap Keyring's responses from `Keyring\Contracts\Responses` with `Keyring::respondWith()`:

| Fortify | Keyring |
|---|---|
| `LoginResponse`, `TwoFactorLoginResponse` | `AuthenticatedResponse` |
| `RegisterResponse` | `RegisterResponse` |
| `FailedTwoFactorLoginResponse` | `FailedResponse` |
| `LockoutResponse` | `LockoutResponse` |
| `LogoutResponse` | `LogoutResponse` |

Keyring adds `ChallengeResponse`, for when another factor is needed. Fortify's password reset and update responses all map to one `StatusResponse`, which carries a status slug such as `reset-link-sent` or `password-updated`. See [Status Responses](https://keyringauth.com/docs/0.x/sign-in-flow#status-responses).

### Events

| Fortify | Keyring |
|---|---|
| `TwoFactorAuthenticationEnabled`, `TwoFactorAuthenticationConfirmed` | `AuthenticatorAdded` |
| `TwoFactorAuthenticationDisabled` | `AuthenticatorRemoved` |
| `RecoveryCodesGenerated` | `RecoveryCodesGenerated` |
| `RecoveryCodeReplaced` | `RecoveryCodeUsed`. Codes aren't replaced one at a time. |
| `TwoFactorAuthenticationChallenged` | `FactorChallenged` |
| `ValidTwoFactorAuthenticationCodeProvided` | `FactorVerified` |
| `TwoFactorAuthenticationFailed` | `FactorFailed` |

All of Keyring's events live in `Keyring\Events`. See [Events](https://keyringauth.com/docs/0.x/events). Laravel's `Login`, `Logout`, `Registered` and `Verified` still fire. Keyring also dispatches Laravel's `Failed`, `Lockout` and `PasswordReset`, so existing listeners for those keep working.

### Rate Limiting

Fortify has two named limiters, `login` and `two-factor`. Keyring limits every factor per account and per IP address inside the pipeline, using `keyring.limits`. An account that keeps failing is locked out for longer each time. See [Rate Limiting](https://keyringauth.com/docs/0.x/security#rate-limiting). Remove your `RateLimiter::for('login', ...)` and `RateLimiter::for('two-factor', ...)` definitions.

Keyring's other form routes, such as registration, password resets, email changes and enrollment, share the `keyring` limiter: 6 requests a minute by default. Define `RateLimiter::for('keyring', ...)` to change it.

## Things That Behave Differently

- **Profile updates can't change the email address.** With `Features::emailChanges()` on, `$user->update(['email' => ...])` throws. Use the [email change flow](https://keyringauth.com/docs/0.x/protected-changes#changing-the-email-address), or `Keyring::withoutProtection()` in admin tooling.
- **Password resets don't sign users in.** They return to the login page, so the second factor still applies. Password resets sign out every session. Password changes sign out the other sessions, unless the request sends `sign_out_others: false`.
- **Sessions end after two hours without activity**, whatever `session.lifetime` says, unless the browser ticked "remember me". To match a longer lifetime, set `sessions.idle`. See [Timeouts](https://keyringauth.com/docs/0.x/devices-and-sessions#timeouts).
- **Remembered browsers sign in once more.** A "remember me" cookie from before the switch is refused the first time it's used. See [Remember Me](https://keyringauth.com/docs/0.x/devices-and-sessions#remember-me).
- **Registering doesn't say when an address is taken, and doesn't sign the new user in.** The user is emailed a verification link and signs in once they've followed it. Your `register` page should say "check your inbox", and your user model must implement `MustVerifyEmail`. To keep Fortify's behaviour, set `registration.reveal_taken`. See [Registration](https://keyringauth.com/docs/0.x/sign-in-flow#registration).
- **The verification link opens a page.** Fortify verifies the address when the link's `GET` arrives. Keyring shows the `email-verification` page, and its button does the verifying. With the default registration flow, the link sends the user to sign in instead, and signing in verifies their address. You only need the page with `registration.reveal_taken`. In tests, post the link's `expires` and `signature` values to its path. See [Email Verification](https://keyringauth.com/docs/0.x/protected-changes#email-verification).
- **Adding a factor needs a fresh verification.** That's a second factor if the user has one, and a verified email if the model implements `MustVerifyEmail`.
- **Recovery codes can't be viewed again.** Users generate a new set. They come automatically with a user's first extra factor.
- **Login errors are the same for unknown accounts and wrong passwords.** The error appears on the username field.
- **The two-factor challenge has its own state.** It's a pending attempt in the session, not `login.id`, and it expires after `pending_logins.keep_for`.
- **Passwords follow OWASP's length rules.** 15 characters without a second factor and 8 with one. Breached passwords are refused. See [Password Rules](https://keyringauth.com/docs/0.x/protected-changes#password-rules).
