# Authentication

- [Introduction](#introduction)
- [Register, login and logout](#register-login-and-logout)
    - [The tokens table](#the-tokens-table)
- [Forgot and reset password](#forgot-and-reset-password)
- [Verifying emails](#verifying-emails)
- [Changing the emails](#changing-the-emails)
- [The profile](#the-profile)
- [Fields and gates on guest routes](#fields-and-gates-on-guest-routes)
- [Settings](#settings)

<a name="introduction"></a>
## Introduction

Restify for PHP gives an application a register, login and logout API with `Route::restifyAuth()`, forgot and reset password, email verification, and a profile API for the logged-in user. This crate serves the same endpoints, with the same requests and answers, so a frontend keeps working after the move to Rust. Links that PHP emailed before the move keep working too.

Each part is off until you turn it on. The login endpoints need the `sanctum` Cargo feature, because they hand out [Sanctum tokens](sanctum.md).

The [OpenAPI document](openapi.md#what-the-document-contains) lists each part you turn on, with the bodies its endpoints accept.

<a name="register-login-and-logout"></a>
## Register, login and logout

Add the Sanctum guard as a provider, then call `auth` with the repository of your user model. This is the example app's `src/lib.rs`:

```rust
use laravel::auth::Authenticate;
use restify::Restify;
use restify::auth::Sanctum;

providers.add(Sanctum::<User>::new());

let restify = Restify::new()
    .authenticate(Authenticate::via::<Sanctum<User>>())
    .auth::<UserRepository>()
    .profile::<UserRepository>()
    .repository::<PostRepository>()
    .repository::<UserRepository>();
```

The user model must derive `Authenticatable` and have `name`, `email` and `password` columns, with an integer key. A new application also needs [the tokens table](#the-tokens-table).

The routes sit directly under `/api`, outside Restify's prefix and middleware, so a guest can reach them:

| Request | Body | Answer |
| --- | --- | --- |
| `POST /api/register` | `name`, `email`, `password`, `password_confirmation` | `200`, the new user and a token |
| `POST /api/login` | `email`, `password` | `200`, the user and a token |
| `POST /api/logout` | Nothing; needs the token | `200`, after deleting the token |

A login or register answer is the user as its repository shows it, with no `data` wrapper, and the token in `meta`:

```json
{
  "id": "2",
  "type": "users",
  "attributes": { "name": "Bob Writer", "is_admin": false, "email_verified_at": null, "created_at": "2026-01-01T10:00:00.000000Z" },
  "meta": {
    "authorizedToShow": false,
    "authorizedToStore": false,
    "authorizedToUpdate": false,
    "authorizedToDelete": false,
    "token": "6|A7Ri79DuX5wxx8sqXmLkIMcwYwZBUCRObjOO2ptF9c670a19",
    "expires_in": null
  }
}
```

The `authorizedTo*` flags of a login or register answer are always `false`, even for an admin, because Restify builds the answer as a guest sees it (see [Fields and gates on guest routes](#fields-and-gates-on-guest-routes)). Don't read permissions from them. Read them from the profile, `GET /api/restify/profile` with the new token, whose `meta` has the user's real flags, or from the user's own attributes, such as a role. Restify for PHP logs the user in first, so its flags are the user's.

The rules are PHP's:

- **Register** needs an email that is valid, at most 255 characters, and not in the users table yet, and a password of at least 6 characters with a matching `password_confirmation`. The email is stored in lower case. The password is hashed with bcrypt, which PHP verifies too. Register writes only `name`, `email`, `password` and the timestamps, so its answer shows every other column as `null`, such as `"is_admin": null`, even when the database gave it a default. A field with `.default(..)` shows that value instead of `null`: a `role` field declared `Field::new(User::role).default("member")` answers `"role": "member"`. PHP answers the same way, because its answer is the model it filled, and a field's `->default()` replaces a `null`.
- **Login** finds the user by the exact email, or else by the email in lower case, and checks the password. A wrong email or password answers `401` with `{"message": "Invalid credentials."}`. An email no account has takes as long to answer as a wrong password, because a login for a missing account spends the time of a bcrypt hash too. So the time of an answer doesn't tell which emails have an account.
- **Logout** deletes the token the request was sent with, so it stops working, and answers `200` with `{"message": "Successfully logged out."}`. The user's other tokens keep working. Restify for PHP deletes the token too, but then answers `500` with `{"message": "Server Error"}`, because of a bug in PHP. A client that ignored the status there works the same here.

### Too many tries

Register and login use PHP's limits. Going over a limit answers `429 Too Many Requests`, with a `Retry-After` header that says how many seconds to wait.

| Route | Limit |
| --- | --- |
| `POST /api/login` | 6 tries a minute for one email from one IP address, and 30 tries a minute from one IP address, whatever the email |
| `POST /api/register` | 6 a minute from one IP address |

Every try counts, whether it succeeds or not, as in PHP. The email counts in lower case. The limits use the framework's rate limiter (its `rate-limiting.md` guide), which keeps its counts in the default cache store. The `memory` store, used when `CACHE_STORE` is not set, keeps one count per process, and loses it on restart. With several servers, set `CACHE_STORE` to `database` or `redis`, so that they share one count.

Two small differences from PHP:

- PHP refills a limit all at once when its minute ends. The framework refills it bit by bit: about one more try every 10 seconds for a limit of 6 a minute.
- PHP counts a login try against its email before it checks the input. Here, a login that fails validation, such as one without a password, counts only toward the 30 a minute from its IP address.

PHP lets an application change these limits by defining its own `restify.login` or `restify.register` limiter. Restify for Rust has no setting for them yet.

Each token is a row in `personal_access_tokens` named `login`, in Sanctum's exact format, so a PHP application that shares the database accepts it. To create tokens yourself, see [Creating tokens](sanctum.md#creating-tokens).

### The tokens table

Register and login store each token in Sanctum's `personal_access_tokens` table, and the guard reads it from there. A database that came from PHP has this table. A new application must create it. Add this migration, such as `database/migrations/2026_12_03_000001_create_personal_access_tokens_table.rs`. It creates the same table as Laravel Sanctum's own migration, as the example app does:

```rust
use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
    tx.schema()
        .create("personal_access_tokens", |table| {
            table.id();
            table.morphs("tokenable");
            table.text("name");
            table.string("token").length(64).unique();
            table.text("abilities").nullable();
            table.timestamp("last_used_at").nullable();
            table.timestamp("expires_at").nullable().index();
            table.timestamps();
        })
        .await
}
```

<a name="forgot-and-reset-password"></a>
## Forgot and reset password

Call `password_reset` with the repository of your user model, next to `auth`. This is the example app's `src/lib.rs`:

```rust
let restify = Restify::new()
    .authenticate(Authenticate::via::<Sanctum<User>>())
    .auth::<UserRepository>()
    .password_reset::<UserRepository>()
    .profile::<UserRepository>();
```

It adds two routes under `/api`, which a guest can reach:

| Request | Body | Answer |
| --- | --- | --- |
| `POST /api/forgotPassword` | `email`, and `url` if you want your own link | `200`, `{"message": "Reset password link sent to your email."}` |
| `POST /api/resetPassword` | `email`, `token`, `password`, `password_confirmation` | `200`, `{"message": "Your password has been successfully reset."}` |

**Forgot password** emails the user a link with a new token in it. It answers the same `200` when no user has that email, so nobody can use it to find out who has an account. A second request for the same email within a minute sends no new email. The link is `{frontend}/password/reset?token={token}&email={email}` by default, where `{frontend}` is `FRONTEND_APP_URL`. Change it with `RESTIFY_PASSWORD_RESET_URL`. A request may send its own `url` with `{token}` and `{email}` in it, such as `https://app.example.com/account/reset?token={token}&email={email}`. Its host must be the host of the reset URL or of `FRONTEND_APP_URL` (`APP_URL` when that is not set), or the answer is `422` "The url host is not allowed.", so nobody can send your users a link to another site.

**Reset password** checks the token and sets the new password. A token works once, for 60 minutes. A wrong, used or expired token answers `400` with `{"message": "Provided invalid token."}`. After a reset, every Sanctum token of the user is deleted, so the user is logged out everywhere. Set `RESTIFY_REVOKE_TOKENS_ON_RESET=false` to keep them. As in PHP, the new password has no minimum length here: add your own check if you need one.

Both answer in at least 200 milliseconds (`RESTIFY_PASSWORD_RESET_TIMEBOX`, in microseconds), whatever happened, so the time an answer takes doesn't tell whether an email has an account.

Tokens are kept in Laravel's `password_reset_tokens` table, in PHP's format: the token hashed with bcrypt, one row per email. A PHP application has this table already. A new one needs it, as the example app's migration creates it. Write it like the [tokens table](#the-tokens-table)'s migration:

```rust
tx.schema()
    .create("password_reset_tokens", |table| {
        table.string("email").primary();
        table.string("token");
        table.timestamp("created_at").nullable();
    })
    .await
```

Because the table and the format are PHP's, a link that PHP emailed before the move still resets the password, and PHP accepts a link that Rust emailed.

<a name="verifying-emails"></a>
## Verifying emails

Call `email_verification` with the repository of your user model. The example app's tests turn it on this way:

```rust
let restify = app::restify().email_verification::<UserRepository>();
```

Then `POST /api/register` also emails the new user a link, and its answer says so in `meta`:

```json
"meta": {
  "email_verification_sent": true,
  "message": "Registration successful. Please check your email to verify your account."
}
```

The link is `POST /api/verify/{id}/{hash}?expires=..&signature=..`. `{hash}` is the SHA-1 of the user's email. The link is signed with `APP_KEY` the way Laravel for PHP signs it, and works for 60 minutes. Keep `APP_KEY` the same as PHP's, and links PHP emailed keep working.

Opening the link sets the user's `email_verified_at` and sends the browser to your frontend with the outcome in the query, as PHP does:

| Case | Answer |
| --- | --- |
| The link is good | `302` to `{frontend}/verify/{id}/{emailHash}?success=true&message=Email+verified+successfully.` |
| The link was changed, never signed, or is older than 60 minutes | `302`, `success=false&message=Invalid+or+expired+verification+link.` |
| The user changed their email since | `302`, `success=false&message=Invalid+hash` |
| The user doesn't exist anymore | `404` |

Opening a good link again answers the same success. Change the page with `RESTIFY_USER_VERIFY_URL`. Set `user_verify_url` to an empty string in code to answer JSON instead: the user, with `meta.message`, or `403` with the message when the link is bad.

The user model needs an `email_verified_at` column. It doesn't need to derive the framework's `MustVerifyEmail`: calling `email_verification` is how you turn it on. Deriving it also makes the framework ask for a verification page on its session guard, which an API doesn't have.

Forgot password, reset password and verify each allow 6 requests a minute from one IP address, as in PHP. The seventh answers `429`, as described in [Too many tries](#too-many-tries).

<a name="changing-the-emails"></a>
## Changing the emails

The emails are the framework's: `ResetPasswordEmail` for a reset link and `VerificationEmail` for a verification link (its `mail.md` and `passwords.md` guides). They are queued and sent with the framework's mailer, so set its `MAIL_*` settings. The framework renders them with MiniJinja: turn on its `minijinja` feature in `Cargo.toml`, as the example app does:

```toml
laravel-rust = { version = "0.2", default-features = false, features = ["database-sqlite", "database-postgres", "minijinja"] }
```

Without it the email can't be rendered. Forgot password still answers `200`, as PHP does when its mailer fails, and the error goes to the log.

The wording is the framework's, not PHP's. To write your own, put the view in your application, where it replaces the framework's:

| Email | Your view | Gets |
| --- | --- | --- |
| Reset link | `resources/views/vendor/laravel/auth/reset-password.html` | `url`, `token` |
| Verification link | `resources/views/vendor/laravel/auth/verify-email.html` | `url` |

<a name="the-profile"></a>
## The profile

`profile::<UserRepository>()` serves the logged-in user at `/api/restify/profile`, behind the provider's middleware:

| Request | Does | Asks `authorize` for |
| --- | --- | --- |
| `GET /api/restify/profile` | Shows the user, as `GET /api/restify/users/{id}` does, with `?related=` | `Show` |
| `PUT /api/restify/profile` | Changes the user with the repository's `Update` input | `Update` |
| `POST /api/restify/profile` | The same as `PUT` | `Update` |

All three answer `{ "data": resource }` with the show fields. Fields the `Update` input doesn't have, such as `is_admin`, are ignored, as in PHP.

`PUT` and `POST` are a full update, as `PUT /api/restify/users/{id}` is, and as Restify for PHP's profile update is. So a `required` rule applies to a key the request leaves out, and each field's `can_update` gate is asked. A field that only admins may change with `can_update(is_admin)` stays closed to other users here too. `can_patch` isn't asked, because the profile has no `PATCH`.

<a name="fields-and-gates-on-guest-routes"></a>
## Fields and gates on guest routes

Register and login have no guard, because the client has no token yet. On such a route, the framework's `request.user()` fails with "no session guard logs in `User`". A `can_see` gate or a policy that reads the user must check `request.authenticated()` first, as the example app's `is_admin` does:

```rust
pub async fn is_admin(request: &Request) -> laravel::Result<bool> {
    // The login and register routes have no guard, and there `request.user()` fails. A guest
    // isn't an admin.
    if !request.authenticated().await? {
        return Ok(false);
    }
    let user: Option<User> = request.user().await?;

    Ok(user.is_some_and(|user| user.is_admin))
}
```

PHP logs the user in before it builds the login answer, so the answer shows the fields that user may see. The framework (`laravel-rust` 0.2) has no public way to log a user into a request without a session guard, so here the login answer shows what a guest may see. A field that only the user may see, such as an admin's own `email`, is missing from it, and the `meta.authorizedTo*` flags are `false`.

<a name="settings"></a>
## Settings

| Variable | `RestifyConfig` field | Default | Does |
| --- | --- | --- | --- |
| `RESTIFY_TOKEN_TTL` | `token_ttl` | none | Minutes a new token lasts. Sets its `expires_at`, and `meta.expires_in` in seconds |
| `SANCTUM_TOKEN_PREFIX` | `SanctumConfig::token_prefix` | empty | Text put before each new token's secret |
| `FRONTEND_APP_URL` | `frontend_app_url` | none | Your frontend's address. Starts the default reset and verify pages, and is a host a reset `url` may use. `APP_URL` is used for that host when this isn't set |
| `RESTIFY_PASSWORD_RESET_URL` | `password_reset_url` | `{frontend}/password/reset?token={token}&email={email}` | The link in the reset email |
| `RESTIFY_USER_VERIFY_URL` | `user_verify_url` | `{frontend}/verify/{id}/{emailHash}` | The page verify sends the browser to. Empty in code: answer JSON |
| `RESTIFY_PASSWORD_RESET_TIMEBOX` | `password_reset_timebox` | `200000` | The shortest time, in microseconds, forgot and reset password take to answer |
| `RESTIFY_REVOKE_TOKENS_ON_RESET` | `revoke_tokens_on_reset` | `true` | Whether a reset deletes the user's Sanctum tokens |
| `SANCTUM_CACHE` | `SanctumConfig::cache` | none | Seconds the guard remembers an accepted token and its user, without asking the database. See [Remembering tokens](sanctum.md#remembering-tokens) for what that changes |

These are the names of PHP's `config/restify.php`. Link lifetimes are Laravel's defaults and can't be changed yet: 60 minutes for a reset token, with one email a minute, and 60 minutes for a verification link.
