Authentication in Laravel Rust, for Laravel developers
Logging in with Auth::attempt's Rust equivalent, sign-up, remember me, throttling, protecting routes, logging out, password changes, resets, email verification and API tokens.
- auth
- security
- getting-started
On this page
Authentication in Laravel Rust works the way it does in Laravel PHP: a session guard that remembers who’s logged in, a user provider that loads them from the users table, “remember me” cookies, password resets and email verification. The building blocks are there out of the box. What a new app doesn’t include is the login, registration and logout routes: those are yours to write, much as you would without a starter kit in PHP. This guide writes them.
The code below runs a coworking space, where members sign up, log in to book desks, and need a verified email to see billing.
The User model
A new app already has this in src/models/user.rs:
#[model]
#[derive(Authenticatable)]
pub struct User {
pub id: i64,
pub name: String,
pub email: String,
pub email_verified_at: Option<Timestamp>,
#[serde(skip)]
pub password: PasswordHash,
#[serde(skip)]
pub remember_token: Option<RememberToken>,
pub created_at: Timestamp,
pub updated_at: Timestamp,
}
Notice the two #[serde(skip)] lines. In PHP you list password and remember_token in $hidden and hope nobody forgets. Here, PasswordHash and RememberToken can’t be serialized at all, so the struct doesn’t compile until you skip them. The hash can’t end up in a JSON response or an Inertia page by accident.
To log in with something other than email, such as a member number, mark that field #[auth(username)].
Logging in
In Laravel PHP:
public function store(Request $request)
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
if (! Auth::attempt($credentials, $request->boolean('remember'))) {
throw ValidationException::withMessages([
'email' => __('auth.failed'),
]);
}
$request->session()->regenerate();
return redirect()->intended(route('desks.index'));
}
In Laravel Rust:
// src/http/handlers/auth.rs
use laravel::auth::Auth;
use laravel::hash::Password;
use laravel::prelude::*;
use crate::models::User;
#[laravel::input]
#[validate(anyone)]
pub struct Login {
#[transform(lowercase)]
#[validate(required, email)]
email: String,
#[validate(required)]
password: Password,
#[serde(default)]
remember: bool,
}
pub async fn login(auth: Auth<User>, form: Valid<Login>) -> laravel::Result<Redirect> {
auth.attempt(&form.email, &form.password)
.remember(form.remember)
.await?;
Ok(Redirect::intended(desks::index, ()))
}
What’s different:
- A wrong password is already a validation error.
attemptsends the browser back to the form with “These credentials do not match our records.” onemail, or a422for JSON. Noifand noValidationException. - The session ID is regenerated for you on success.
passwordis aPassword, not aString. It keeps the plain text out of logs, and fails validation if it’s too long to hash.#[transform(lowercase)]on the email matters more than in PHP with MySQL: on PostgreSQL and SQLite, text comparison is case-sensitive, soAna@example.comandana@example.comwould be different users.#[validate(anyone)]says guests may submit this form. Every input struct must say who may submit it, or it won’t compile.Redirect::intendedtakes the handler, not a route name, as a fallback.
A remembered user gets an encrypted cookie that lasts 400 days. If you raise BCRYPT_ROUNDS later, attempt rehashes each user’s password with the new cost the next time they log in.
Throttling the login form
In PHP the Breeze starter does this in its LoginRequest. Here you add it to the handler: check the limit, count only failures, and clear the counter on success. ValidRequest<T> gives you the validated form plus the request, so you can read the IP:
use laravel::rate_limit::{self, Limit};
use laravel::validation::ValidRequest;
pub async fn login(auth: Auth<User>, login: ValidRequest<Login>) -> laravel::Result<Redirect> {
let limit = Limit::per_minute(5);
let key = format!("login:{}|{}", login.email, login.request().ip());
rate_limit::check(&key, limit).await??;
if let Err(error) = auth.attempt(&login.email, &login.password)
.remember(login.remember)
.await
{
rate_limit::hit(&key, limit).await?;
return Err(error);
}
rate_limit::clear(&key).await?;
Ok(Redirect::intended(desks::index, ()))
}
Signing up
use laravel::model::create;
#[laravel::input]
#[validate(anyone)]
pub struct SignUp {
#[validate(required, max_length(255))]
name: String,
#[transform(lowercase)]
#[validate(required, email, unique(User::email))]
email: String,
#[validate(required, password, confirmed)]
password: Password,
}
pub async fn sign_up(auth: Auth<User>, Valid(form): Valid<SignUp>) -> laravel::Result<Redirect> {
let member = create!(User {
name: &form.name,
email: &form.email,
password: &form.password,
})
.await?;
auth.login(&member).await?;
Ok(redirect!(desks::index))
}
create! hashes the password itself, so there’s no Hash::make. unique(User::email) refers to the column through the model, so a typo in the column name is a compile error. auth.login(&user) is Auth::login($user).
Who’s logged in
| Laravel PHP | Laravel Rust |
|---|---|
$request->user() on a protected route |
Take user: Authenticated<User> as an argument |
Auth::user() where guests are allowed |
auth.user().await?, an Option<User> |
Auth::check() |
auth.check().await? |
Auth::id() |
auth.id().await? |
Authenticated<User> is the one you’ll use most. If a guest reaches a handler that asks for it, they’re sent to the login page (or get a 401 for JSON) before the handler runs, so inside the handler there’s always a user:
pub async fn index(member: Authenticated<User>) -> Page {
inertia::render("Desks/Index", props! { "name" => &member.name })
}
Protecting routes
Authenticate is PHP’s auth middleware, and RedirectIfAuthenticated is guest:
use laravel::auth::{Authenticate, RedirectIfAuthenticated};
pub fn routes(route: &mut Router) {
route.middleware(RedirectIfAuthenticated).group(|route| {
route.get("/login", auth::show_login);
route.post("/login", auth::login);
route.get("/join", auth::show_sign_up);
route.post("/join", auth::sign_up);
});
route.middleware(Authenticate).group(|route| {
route.get("/desks", desks::index);
route.post("/logout", auth::logout);
});
}
How does Authenticate know where your login page is, when there are no route names? You mark the handler:
#[laravel::auth::page(login)]
pub async fn show_login() -> Page {
inertia::render("Auth/Login", props! {})
}
There are markers for login, home (where RedirectIfAuthenticated sends logged-in users), reset_password, verification_notice and verify_email. Mark only the pages your app has.
Logging out
use laravel::inertia::Inertia;
pub async fn logout(auth: Auth<User>, inertia: Inertia) -> laravel::Result<Redirect> {
auth.logout().await?;
inertia.clear_history();
Ok(Redirect::to("/"))
}
logout does in one call what PHP does in three (Auth::logout(), invalidate(), regenerateToken()), and it also invalidates the user’s remember-me cookies on every device. clear_history pairs with Inertia’s history encryption, so the back button can’t show a page from the logged-in session.
Changing and resetting passwords
Changing a password logs the member out everywhere else, which is what you want if someone else had their password:
#[laravel::input]
#[validate(authenticated)]
pub struct UpdatePassword {
#[validate(required, current_password)]
current_password: Password,
#[validate(required, password, confirmed)]
password: Password,
}
pub async fn update_password(
auth: Auth<User>,
Valid(form): Valid<UpdatePassword>,
) -> laravel::Result<Redirect> {
auth.update_password(&form.password).await?;
Ok(Redirect::back().with("status", "Password updated."))
}
This happens whenever the stored hash changes, even from a console command, because each session carries a signed fingerprint of the hash. Calling update_password with the user’s current password is also how you build “log out my other devices”.
For forgotten passwords, the Passwords<User> extractor replaces PHP’s Password facade: send_reset_link(&email) and reset(&email, &token, &password). You write the four routes and forms. A few details from the docs:
Userneedsimpl From<&User> for Addressso the reset email has a recipient.- Reset emails are queued, so a queue worker must be running.
- Tokens live in the cache. With several servers, use a shared store such as
databaseorredis. send_reset_linkbehaves the same whether or not the email has an account, so keep your status message identical too.- Tokens are single-use and expire after 60 minutes. A reset doesn’t log the user in unless you call
auth.loginwith the userresetreturns.
Requiring a verified email
Derive MustVerifyEmail on User, add the notice, resend and verify routes behind Authenticate, and send the first link from your sign-up handler with the EmailVerification<User> extractor. Then guard the pages that need it:
use laravel::auth::{Authenticate, RequireVerifiedEmail};
route.middleware(Authenticate).middleware(RequireVerifiedEmail).group(|route| {
route.get("/billing", billing::show);
});
That’s PHP’s verified middleware. Unverified members are sent to your notice page; JSON requests get a 403.
API tokens
For bearer tokens, the docs show a guard you write yourself rather than a package like Sanctum. You implement RequestGuard on a service: its user method reads the request and returns the matching user or None. Protect routes with Authenticate::via::<YourGuard>(), and Authenticated<User> works in those handlers as usual. The docs’ example stores a SHA-256 hash of each token rather than the token itself, which is good practice whatever framework you use.
One caveat: routes in the api group have no session, so login, attempt, logout and update_password return a server error there.
Testing
#[laravel::test]
async fn members_can_log_in(app: Application) -> laravel::Result<()> {
let member = create!(User::factory() { password: "correct-horse" }).await?;
app.post("/login")
.form([("email", member.email.as_str()), ("password", "correct-horse")])
.await
.assert_redirect_to("/desks")
.assert_authenticated_as(&member);
Ok(())
}
acting_as(&user) skips the login for other tests, and assert_guest() checks a failed attempt. More in Testing in Laravel Rust.
Quick reference
| Laravel PHP | Laravel Rust |
|---|---|
Auth::attempt($credentials, $remember) |
auth.attempt(&email, &password).remember(r).await? |
Auth::login($user) |
auth.login(&user).await? |
Auth::logout() + invalidate + regenerate |
auth.logout().await? |
$request->user() |
Authenticated<User> argument |
auth middleware |
Authenticate |
guest middleware |
RedirectIfAuthenticated |
verified middleware |
RequireVerifiedEmail |
$hidden = ['password'] |
Enforced by the types |
Password::sendResetLink(...) |
passwords.send_reset_link(&email) |
| Sanctum tokens | Your own RequestGuard |