Authentication
- Introduction
- Setting up
- Logging users in
- Retrieving the logged-in user
- Protecting routes
- Logging out
- Changing a password
- Stateless authentication
- Testing
Introduction
dust-framework provides built-in authentication backed by sessions and "remember me" cookies, along with password resets and email verification, while letting your application control its own login pages and forms. If you want users to sign in with Google, GitHub, or Microsoft, check out the Social login guide.
Authentication works through a "guard" and a "user provider". The guard identifies the user for each incoming request, while the provider loads that user from storage, typically your users table. The built-in session guard uses the session cookie on web routes; for token-based APIs, you can define a request guard.
| Your application needs | Use |
|---|---|
| A login form for browser pages | The session guard and Authenticate |
| A stateless API or mobile client | A request guard with a bearer token |
| Sign-in with Google, GitHub, or Microsoft | Social login |
| Forgotten passwords | Password resets |
| A confirmed email before sensitive pages | Email verification |
Once authentication determines who the user is, authorization decides which actions they are permitted to perform.
Setting up
New applications include a User model, a users migration, and the session guard registered in src/app.rs, while leaving login, registration, and logout routes up to your application. The sections below walk through each piece so you can customize them, such as signing users in by username instead of email.
Your user type
Your user is a model that derives Authenticatable. The derive reads the user's ID, password hash, and remember token from the id, password, and remember_token fields. The default User model in src/models/user.rs looks like this:
use dust::auth::{Authenticatable, RememberToken};use dust::hash::PasswordHash;use dust::model::model;use dust::time::Timestamp;#[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,}Neither PasswordHash nor RememberToken implements Serialize, so User compiles only once you skip both fields. That way, neither the password hash nor the remember token can leak into a page or JSON response.
Users log in with their email address. To log them in by another column, such as a username, mark its field with #[auth(username)].
The users table needs a password column and a nullable remember_token column. The default migration creates both:
tx.schema() .create("users", |table| { table.id(); table.string("name"); table.string("email").unique(); table.timestamp("email_verified_at").nullable(); table.string("password"); table.remember_token(); table.timestamps(); }) .awaitRegistering the session guard
The session guard keeps the logged-in user's ID in the session, and asks a provider for the user on each request. When your users are a model, the provider is model::Users, which finds them with the model's queries. Register the guard with it in src/app.rs:
use dust::model;use crate::models::User;Application::configure() .with_auth(|auth, _| { auth.session::<model::Users<User>>(); })model::Users looks up users by their email address (or whichever column is marked #[auth(username)]). If you need to block specific accounts from accessing your application, such as suspended users, you can reject their requests in a middleware or check their account status during login.
An application registers a single session guard for one user type. For roles such as administrators, store the role on your User model and check it in a policy.
Marking pages
dust-framework needs to know which routes serve a few core authentication pages so it can redirect guests to your login form and generate password reset or email verification links. Annotate each corresponding handler with #[dust::auth::page(..)]:
use dust::auth::Authenticated;use dust::prelude::*;use dust::view::View;#[dust::auth::page(login)]pub async fn show_login() -> View { view("auth.login", data! {})}#[dust::auth::page(home)]pub async fn dashboard(user: Authenticated<User>) -> View { view("dashboard", data! { user })}The attribute doesn't change the handler, so you route it and link to it as usual. You do not need to mark every page; only annotate the ones your application actually uses (for example, omit verification_notice and verify_email if your application does not require email verification):
| Attribute | Page | Who sends users there |
|---|---|---|
#[dust::auth::page(login)] |
The login page | Authenticate, for guests |
#[dust::auth::page(home)] |
The logged-in user's home, such as a dashboard | RedirectIfAuthenticated, for logged-in users |
#[dust::auth::page(reset_password)] |
The form that sets a new password | The link in password reset emails |
#[dust::auth::page(verification_notice)] |
The page that asks the user to verify their email | RequireVerifiedEmail, for users who haven't |
#[dust::auth::page(verify_email)] |
The handler that verifies the email | The link in verification emails |
Logging users in
Users log in through a form on your login page. The handler that the form posts to checks the user's email and password, then stores the user in the session, so your handlers can retrieve them on later requests.
Attempting a login
In that handler, take Auth<User> as an argument and call attempt with the email and password from the form. It finds the user, checks the password, and logs them in:
use dust::auth::Auth;use dust::hash::Password;use dust::prelude::*;#[dust::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>) -> dust::Result<Redirect> { auth.attempt(&form.email, &form.password).remember(form.remember).await?; Ok(Redirect::intended(dashboard::show, ()))}The form declares its password field as dust::hash::Password rather than a String. A Password keeps the plain-text password out of your logs, and fails validation on the field when a password is too long to hash. To learn more, check out the hashing guide's section on password fields.
When the email or password is wrong, attempt returns a validation error. The browser goes back to the form with "These credentials do not match our records." on the email field, and a JSON client gets a 422. If User marks a field #[auth(username)], the error goes on that field instead, so give the form field the same name.
On success, attempt regenerates the session ID, stores the user in the session, and returns the user. Redirect::intended sends the user back to the URL they originally tried to visit before Authenticate redirected them to login, falling back to the route you specify.
dust-framework hashes passwords using Bcrypt. When you raise BCRYPT_ROUNDS, attempt automatically rehashes the user's password with the new work factor on their next login, as Hashing describes.
Throttling login attempts
Throttle your login handler so an attacker can't try thousands of passwords a minute. To count only failed attempts and clear the counter once the user signs in, extract ValidRequest<Login> so you have the client's IP address, check the rate limit before calling attempt, and call hit only on failure:
use dust::auth::Auth;use dust::prelude::*;use dust::rate_limit::{self, Limit};use dust::validation::ValidRequest;pub async fn login(auth: Auth<User>, login: ValidRequest<Login>) -> dust::Result<Redirect> { let limit = Limit::per_minute(5); let key = format!("login:{}|{}", login.email.to_lowercase(), 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(dashboard::show, ()))}Remembering users
Many applications show a "remember me" checkbox on their login form. Pass its boolean value to remember when calling attempt:
auth.attempt(&form.email, &form.password) .remember(form.remember) .await?;A remembered user receives an encrypted cookie that lasts 400 days. After their session expires, the cookie signs them back in automatically on their next visit.
Logging in a user you already have
To log in a user without checking a password, such as immediately after registration, pass them to login:
use dust::auth::Auth;use dust::hash::Password;use dust::model::create;use dust::prelude::*;#[dust::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>,) -> dust::Result<Redirect> { let user = create!(User { name: &form.name, email: &form.email, password: &form.password, }) .await?; auth.login(&user).await?; Ok(redirect!(dashboard::show))}create! hashes the password for you, so the plain text never reaches your database. login also takes .remember(true).
On PostgreSQL and SQLite, text comparisons are case-sensitive, so Taylor@example.com and taylor@example.com don't match during sign-up or login. Adding #[transform(lowercase)] normalizes the email address before unique(User::email) and attempt run. To learn more, check out the validation guide's section on transforming input fields.
Handling a failed login yourself
Internally, attempt calls validate followed by login. When you want custom behavior on failure, call both methods yourself: validate checks the email and password and returns Option<User> without signing the user in.
For example, suppose your users table has a nullable suspended_at column. This handler for the Login form above logs failed attempts and informs suspended users why their account is locked:
use dust::auth::Auth;use dust::prelude::*;use dust::validation::invalid;pub async fn login(auth: Auth<User>, form: Valid<Login>) -> dust::Result<Redirect> { let Some(user) = auth.validate(&form.email, &form.password).await? else { tracing::info!(email = form.email, "failed login"); invalid!(email => "These credentials do not match our records."); }; if user.suspended_at.is_some() { invalid!(email => "This account has been suspended."); } auth.login(&user).remember(form.remember).await?; Ok(Redirect::intended(dashboard::show, ()))}Retrieving the logged-in user
For handlers that require an authenticated user, extract Authenticated<User>, which dereferences directly to your User model:
use dust::auth::Authenticated;use dust::prelude::*;use dust::view::View;pub async fn show(user: Authenticated<User>) -> View { view("dashboard", data! { name => &user.name })}If a guest hits the route, dust-framework redirects them to the login page (or responds with 401 for JSON requests) before the handler runs, matching the Authenticate middleware.
For routes accessible to both guests and signed-in users, extract Auth<User> and call auth.user().await?, which returns Option<User>:
use dust::auth::Auth;use dust::prelude::*;use dust::view::View;pub async fn home(auth: Auth<User>) -> dust::Result<View> { let name = auth.user().await?.map(|user| user.name); Ok(view("home", data! { name }))}Auth<User> also provides check() (returning a bool) and id() (returning Option<Id>), and works anywhere extractors are supported, including middleware:
if auth.check().await? { // The user is logged in...}if let Some(user_id) = auth.id().await? { // ...}When you have a &Request without extractors, such as inside a middleware, call request.user() with an explicit type annotation:
let user: Option<User> = request.user().await?;If you only need to check whether someone is signed in without loading the model, call request.authenticated(), which returns a bool without requiring a type parameter:
if request.authenticated().await? { // ...}dust-framework caches the resolved user for the duration of the request, so Auth, Authenticated, request.user(), and request.authenticated() all share the same lookup.
Protecting routes
The Authenticate middleware lets only logged-in users through. Attach it to a group of routes in your route file:
use dust::auth::Authenticate;use dust::prelude::*;pub fn routes(route: &mut Router) { route.middleware(Authenticate).group(|route| { route.get("/dashboard", dashboard::show); route.get("/settings", settings::show); });}| You want to | Reach for |
|---|---|
| Reject guests before the handler runs | Authenticate middleware |
| Send logged-in users away from login and registration pages | RedirectIfAuthenticated |
| Receive the user as a handler argument | Authenticated<User> |
| Handle guests and users in the same handler | Auth<User> and auth.user().await? |
| Require a confirmed email address | RequireVerifiedEmail |
Redirecting guests
Authenticate sends a guest to the login page. If the guest was visiting a page with GET, the session stores that URL so Redirect::intended can redirect them back after logging in. A request expecting JSON, or an application without a login page, receives a 401 instead.
Pages for guests only
The RedirectIfAuthenticated middleware sends logged-in users to the home page, or else to /. Use it for pages that only guests need, such as the login page:
use dust::auth::RedirectIfAuthenticated;route.middleware(RedirectIfAuthenticated).group(|route| { route.get("/login", auth::show_login); route.post("/login", auth::login);});Logging out
To log the user out, call logout. It clears the session, regenerates the session ID and CSRF token, and invalidates the user's "remember me" cookies across all devices:
use dust::auth::Auth;use dust::prelude::*;pub async fn logout(auth: Auth<User>) -> dust::Result<Redirect> { auth.logout().await?; Ok(Redirect::to("/"))}After a logout, the browser's back button may still show a page the user saw while logged in, because the browser cached the HTML. If that matters for your application, add a no_store cache header to the routes that show private pages, so the browser fetches them again and the guest is redirected to the login page.
Logging out other devices
To sign a user out of their other active sessions without logging out their current device, confirm their current password and pass it to update_password:
use dust::auth::Auth;use dust::hash::Password;use dust::prelude::*;#[dust::input]#[validate(authenticated)]pub struct LogoutOtherDevices { #[validate(required, current_password)] password: Password,}pub async fn logout_other_devices( auth: Auth<User>, Valid(form): Valid<LogoutOtherDevices>,) -> dust::Result<Redirect> { auth.update_password(&form.password).await?; Ok(Redirect::back().with("status", "You're logged out on your other devices."))}Under the hood, dust-framework stores a signed fingerprint of the user's password hash in each session and "remember me" cookie and verifies it on every request. Because Bcrypt generates a new random salt every time it hashes a password, calling update_password produces a different stored hash even for the same password. dust-framework refreshes the fingerprint on the current device (keeping it signed in), while every other device's session and "remember me" cookie fails the fingerprint check on its next request and is automatically logged out.
Changing a password
To change the logged-in user's password, call update_password. It hashes the password, stores the hash, and keeps the current device logged in. Ask for the current password too, so someone who finds the user's laptop unlocked can't take over the account:
use dust::auth::Auth;use dust::hash::Password;use dust::prelude::*;#[dust::input]#[validate(authenticated)]pub struct UpdatePassword { #[validate(required, current_password)] current_password: Password, #[validate(required, password, confirmed)] password: Password,}pub async fn update( auth: Auth<User>, Valid(form): Valid<UpdatePassword>,) -> dust::Result<Redirect> { auth.update_password(&form.password).await?; Ok(Redirect::back().with("status", "Password updated."))}Changing a password logs the user out of every other session and "remember me" cookie, including any an attacker is using. This happens whenever the stored hash changes, even when you store it another way, such as from a console command.
Stateless authentication
API clients, such as mobile apps or other servers, typically authenticate each request with a bearer token, API key header, or signed credential instead of a session cookie. To authenticate stateless requests, implement RequestGuard on a service. Its user method inspects the incoming Request and returns the matching user, or None if the request cannot be authenticated.
Store a hash of each API token rather than the plaintext token so a database leak does not expose live credentials. Suppose your users table has an api_token column holding a SHA-256 hash computed with the sha2 and hex crates, installed with cargo add sha2 hex. This guard, in src/http/guards.rs, reads the bearer token from the Authorization: Bearer header:
use dust::auth::RequestGuard;use dust::container::singleton;use dust::prelude::*;use sha2::{Digest, Sha256};use crate::models::User;#[singleton]pub struct ApiTokens;impl RequestGuard for ApiTokens { type User = User; async fn user(&self, request: &Request) -> dust::Result<Option<User>> { let Some(token) = request.bearer_token() else { return Ok(None); }; let hash = hex::encode(Sha256::digest(token)); User::first_where(User::api_token.eq(hash)).await }}To protect routes with the guard, use Authenticate::via, which runs the guard for each request:
use dust::auth::Authenticate;route.middleware(Authenticate::via::<ApiTokens>()).group(|route| { route.get("/me", users::me);});If the guard returns None, dust-framework returns the same unauthenticated response as Authenticate: 401 for JSON requests, or a redirect to the login page for browser requests. Otherwise, Authenticated<User>, Auth<User>, and request.user() resolve to the authenticated user:
use dust::prelude::*;pub async fn me(Authenticated(user): Authenticated<User>) -> Json<User> { Json(user)}A request guard needs no session, so it works on routes in the api group. Because there's no session there, login, attempt, logout, and update_password return a server error on those routes.
Testing
To send a test request as a logged-in user, use acting_as:
use app::models::User;use dust::testing::prelude::*;#[dust::test]async fn the_dashboard_greets_the_user(app: Application) -> dust::Result<()> { let user = User::factory().create().await?; app.get("/dashboard") .acting_as(&user) .await .assert_ok() .assert_see(&format!("Hello, {}", user.name)); Ok(())}acting_as works on routes that a request guard protects too, without running the guard.
To test logging in itself, create a user with a factory and post their credentials to your login route:
use app::models::User;use dust::model::create;use dust::testing::prelude::*;#[dust::test]async fn users_can_log_in(app: Application) -> dust::Result<()> { let user = create!(User::factory() { password: "password" }).await?; let response = app .post("/login") .form([("email", user.email.as_str()), ("password", "password")]) .await; response .assert_redirect_to("/dashboard") .assert_authenticated_as(&user); app.get("/dashboard") .with_cookies_from(&response) .await .assert_ok(); Ok(())}assert_authenticated verifies that a user is signed into the session, assert_authenticated_as(&user) verifies which user is signed in, and assert_guest confirms that no user is authenticated (such as after submitting an invalid password). Passing with_cookies_from(&response) carries the response's session cookie into the next request.