Skip to content

Resetting Passwords

Security

Resetting Passwords

Introduction

Laravel can handle generating and verifying password reset tokens, sending reset emails, and updating user passwords through the Passwords<User> extractor, while leaving your application in charge of the routes and forms.

Before getting started, configure authentication so users can sign in.

Preparing your application

Laravel sends password reset emails using the mail system by passing your user to mail::to(&user). To make User usable as a recipient, implement From<&User> for Address in src/models/user.rs (see Recipients):

1use laravel::mail::Address;
2 
3impl From<&User> for Address {
4 fn from(user: &User) -> Self {
5 Address::new(&user.email).with_name(&user.name)
6 }
7}
1use laravel::mail::Address;
2 
3impl From<&User> for Address {
4 fn from(user: &User) -> Self {
5 Address::new(&user.email).with_name(&user.name)
6 }
7}

Reset emails are queued so the response doesn't wait for your mail provider, which means a queue worker must be running to deliver them.

Laravel keeps reset tokens in your default cache store. When you run more than one server, use a store that every server shares, such as database or redis, not memory.

Reset links start with the request's host. In production, Laravel answers only requests for the host in your APP_URL and its subdomains, so a forged Host header can't point a link at another site. If you serve other domains too, add them to your trusted hosts.

Routing

A reset needs four routes: two to show the forgot password form and send the link, and two to show the reset form and save the new password. Add them to your web routes, behind RedirectIfAuthenticated, which sends a user who is already logged in to their home page instead:

1use laravel::auth::RedirectIfAuthenticated;
2 
3route.middleware(RedirectIfAuthenticated).group(|route| {
4 route.get("/forgot-password", passwords::show_forgot_password);
5 route.post("/forgot-password", passwords::send_reset_link);
6 route.get("/reset-password/{token}", passwords::show_reset_password);
7 route.post("/reset-password", passwords::reset_password);
8});
1use laravel::auth::RedirectIfAuthenticated;
2 
3route.middleware(RedirectIfAuthenticated).group(|route| {
4 route.get("/forgot-password", passwords::show_forgot_password);
5 route.post("/forgot-password", passwords::send_reset_link);
6 route.get("/reset-password/{token}", passwords::show_reset_password);
7 route.post("/reset-password", passwords::reset_password);
8});

Your forgot password page should show a form with an email field. When the user submits it, validate the email and pass it to send_reset_link, which emails the user a link to your reset page:

1use laravel::auth::Passwords;
2use laravel::inertia::{self, Page, props};
3use laravel::prelude::*;
4 
5#[laravel::input]
6#[validate(anyone)]
7pub struct ForgotPassword {
8 #[validate(required, email)]
9 email: String,
10}
11 
12pub async fn show_forgot_password() -> Page {
13 inertia::render("auth/ForgotPassword", props! {})
14}
15 
16pub async fn send_reset_link(
17 passwords: Passwords<User>,
18 Valid(form): Valid<ForgotPassword>,
19) -> laravel::Result<Redirect> {
20 passwords.send_reset_link(&form.email).await?;
21 
22 Ok(
23 Redirect::back()
24 .with("status", "If that email has an account, we've sent it a reset link."),
25 )
26}
1use laravel::auth::Passwords;
2use laravel::inertia::{self, Page, props};
3use laravel::prelude::*;
4 
5#[laravel::input]
6#[validate(anyone)]
7pub struct ForgotPassword {
8 #[validate(required, email)]
9 email: String,
10}
11 
12pub async fn show_forgot_password() -> Page {
13 inertia::render("auth/ForgotPassword", props! {})
14}
15 
16pub async fn send_reset_link(
17 passwords: Passwords<User>,
18 Valid(form): Valid<ForgotPassword>,
19) -> laravel::Result<Redirect> {
20 passwords.send_reset_link(&form.email).await?;
21 
22 Ok(
23 Redirect::back()
24 .with("status", "If that email has an account, we've sent it a reset link."),
25 )
26}

When no user matches the email, send_reset_link sends nothing and returns the same outcome so the response never reveals whether an account exists. Keep your status message identical in both cases. If the user requests another link within 60 seconds, send_reset_link skips sending; otherwise, the new link replaces the previous one.

Resetting the password

The link in the email opens the handler you marked with #[laravel::auth::page(reset_password)]. The reset token arrives in the {token} route parameter and the email address arrives in the query string, as in https://acme.test/reset-password/4Fq…?email=taylor%40laravel.com.

Your reset page should show a form with the email, a new password and its confirmation, and the token in a hidden field. When the user submits it, pass the form's values to reset:

1use laravel::auth::Passwords;
2use laravel::hash::Password;
3use laravel::inertia::{self, Page, props};
4use laravel::prelude::*;
5 
6#[laravel::input]
7#[validate(anyone)]
8pub struct ResetPassword {
9 #[validate(required)]
10 token: String,
11 #[validate(required, email)]
12 email: String,
13 #[validate(required, password, confirmed)]
14 password: Password,
15}
16 
17#[laravel::query]
18pub struct ResetLink {
19 #[default]
20 email: String,
21}
22 
23#[laravel::auth::page(reset_password)]
24pub async fn show_reset_password(
25 Params(token): Params<String>,
26 Query(ResetLink { email }): Query<ResetLink>,
27) -> Page {
28 inertia::render(
29 "auth/ResetPassword",
30 props! { "token" => token, "email" => email },
31 )
32}
33 
34pub async fn reset_password(
35 passwords: Passwords<User>,
36 Valid(form): Valid<ResetPassword>,
37) -> laravel::Result<Redirect> {
38 passwords.reset(&form.email, &form.token, &form.password).await?;
39 
40 Ok(redirect!(auth::show_login).with("status", "Your password has been reset."))
41}
1use laravel::auth::Passwords;
2use laravel::hash::Password;
3use laravel::inertia::{self, Page, props};
4use laravel::prelude::*;
5 
6#[laravel::input]
7#[validate(anyone)]
8pub struct ResetPassword {
9 #[validate(required)]
10 token: String,
11 #[validate(required, email)]
12 email: String,
13 #[validate(required, password, confirmed)]
14 password: Password,
15}
16 
17#[laravel::query]
18pub struct ResetLink {
19 #[default]
20 email: String,
21}
22 
23#[laravel::auth::page(reset_password)]
24pub async fn show_reset_password(
25 Params(token): Params<String>,
26 Query(ResetLink { email }): Query<ResetLink>,
27) -> Page {
28 inertia::render(
29 "auth/ResetPassword",
30 props! { "token" => token, "email" => email },
31 )
32}
33 
34pub async fn reset_password(
35 passwords: Passwords<User>,
36 Valid(form): Valid<ResetPassword>,
37) -> laravel::Result<Redirect> {
38 passwords.reset(&form.email, &form.token, &form.password).await?;
39 
40 Ok(redirect!(auth::show_login).with("status", "Your password has been reset."))
41}

Make the email field read-only, with autocomplete="username", so a password manager saves the new password for that account.

reset verifies the reset token, stores the new password, and returns the user. Each reset token is single-use and valid for 60 minutes. If a reset token is invalid or expired, reset returns a validation error on the email field with the message "This password reset token is invalid.", so display errors for that field. Like changing a password, a reset logs the user out on every device.

Logging the user in after a reset

reset doesn't log the user in. To log them in instead of sending them to the login page, pass the user that reset returns to login:

1use laravel::auth::{Auth, Passwords};
2use laravel::prelude::*;
3 
4pub async fn reset_password(
5 passwords: Passwords<User>,
6 auth: Auth<User>,
7 Valid(form): Valid<ResetPassword>,
8) -> laravel::Result<Redirect> {
9 let user = passwords.reset(&form.email, &form.token, &form.password).await?;
10 
11 auth.login(&user).await?;
12 
13 Ok(redirect!(dashboard::show))
14}
1use laravel::auth::{Auth, Passwords};
2use laravel::prelude::*;
3 
4pub async fn reset_password(
5 passwords: Passwords<User>,
6 auth: Auth<User>,
7 Valid(form): Valid<ResetPassword>,
8) -> laravel::Result<Redirect> {
9 let user = passwords.reset(&form.email, &form.token, &form.password).await?;
10 
11 auth.login(&user).await?;
12 
13 Ok(redirect!(dashboard::show))
14}

A user may open an expired or already-used link. To notify them before they enter a new password, call validate on the reset page. It returns the matching user, or None, without consuming the reset token:

1use laravel::auth::Passwords;
2use laravel::inertia::{self, Page, props};
3use laravel::prelude::*;
4 
5#[laravel::auth::page(reset_password)]
6pub async fn show_reset_password(
7 passwords: Passwords<User>,
8 Params(token): Params<String>,
9 Query(ResetLink { email }): Query<ResetLink>,
10) -> laravel::Result<Page> {
11 if passwords.validate(&email, &token).await?.is_none() {
12 return Ok(inertia::render("auth/ResetLinkExpired", props! {}));
13 }
14 
15 Ok(inertia::render(
16 "auth/ResetPassword",
17 props! { "token" => token, "email" => email },
18 ))
19}
1use laravel::auth::Passwords;
2use laravel::inertia::{self, Page, props};
3use laravel::prelude::*;
4 
5#[laravel::auth::page(reset_password)]
6pub async fn show_reset_password(
7 passwords: Passwords<User>,
8 Params(token): Params<String>,
9 Query(ResetLink { email }): Query<ResetLink>,
10) -> laravel::Result<Page> {
11 if passwords.validate(&email, &token).await?.is_none() {
12 return Ok(inertia::render("auth/ResetLinkExpired", props! {}));
13 }
14 
15 Ok(inertia::render(
16 "auth/ResetPassword",
17 props! { "token" => token, "email" => email },
18 ))
19}

Customizing the reset email

By default, Laravel sends password reset links using the built-in laravel::auth::ResetPasswordEmail mailable, which uses the subject "Reset your password" and renders with Laravel's mail components.

To customize the email's wording or layout without writing a custom mailable, copy resources/views/auth/reset-password.html to resources/views/vendor/laravel/auth/reset-password.html in your application and edit it to fit your brand. The template receives url for the reset link and minutes for the expiration window.

To send a custom mailable, such as a ResetYourPassword email greeting the user by name, call send_reset_link_with. It generates a reset token and passes both the user and reset token to your closure so you can build the link and queue the email. Because each reset token is bound to the email address passed in, include that same email address in the link:

1use laravel::auth::Passwords;
2use laravel::mail;
3use laravel::prelude::*;
4 
5pub async fn send_reset_link(
6 passwords: Passwords<User>,
7 Valid(form): Valid<ForgotPassword>,
8) -> laravel::Result<Redirect> {
9 passwords
10 .send_reset_link_with(&form.email, async |user, token| {
11 let url = route!(show_reset_password, token = &token, email = &form.email)?;
12 
13 mail::to(&user).queue(ResetYourPassword { name: user.name.clone(), url }).await
14 })
15 .await?;
16 
17 Ok(
18 Redirect::back()
19 .with("status", "If that email has an account, we've sent it a reset link."),
20 )
21}
1use laravel::auth::Passwords;
2use laravel::mail;
3use laravel::prelude::*;
4 
5pub async fn send_reset_link(
6 passwords: Passwords<User>,
7 Valid(form): Valid<ForgotPassword>,
8) -> laravel::Result<Redirect> {
9 passwords
10 .send_reset_link_with(&form.email, async |user, token| {
11 let url = route!(show_reset_password, token = &token, email = &form.email)?;
12 
13 mail::to(&user).queue(ResetYourPassword { name: user.name.clone(), url }).await
14 })
15 .await?;
16 
17 Ok(
18 Redirect::back()
19 .with("status", "If that email has an account, we've sent it a reset link."),
20 )
21}

Because a reset token allows changing the user's password, keep it out of unencrypted storage. Queue the email via mail::to(..).queue(..), which encrypts queued mail, rather than placing the reset token in a plain queued job.

Testing

To test a password reset, fake mail, read the token from the queued ResetPasswordEmail, and submit the reset form with it:

1use app::models::User;
2use laravel::auth::ResetPasswordEmail;
3use laravel::mail;
4use laravel::testing::prelude::*;
5 
6#[laravel::test]
7async fn users_can_reset_their_password(app: Application) -> laravel::Result<()> {
8 let mail = mail::fake();
9 let user = User::factory().create().await?;
10 
11 app.post("/forgot-password")
12 .form([("email", user.email.as_str())])
13 .await
14 .assert_redirect();
15 
16 let emails = mail.queued::<ResetPasswordEmail>();
17 let token = &emails[0].mailable().token;
18 
19 app.post("/reset-password")
20 .form([
21 ("token", token.as_str()),
22 ("email", user.email.as_str()),
23 ("password", "new-password"),
24 ("password_confirmation", "new-password"),
25 ])
26 .await
27 .assert_redirect_to(route!(auth::show_login)?);
28 
29 Ok(())
30}
1use app::models::User;
2use laravel::auth::ResetPasswordEmail;
3use laravel::mail;
4use laravel::testing::prelude::*;
5 
6#[laravel::test]
7async fn users_can_reset_their_password(app: Application) -> laravel::Result<()> {
8 let mail = mail::fake();
9 let user = User::factory().create().await?;
10 
11 app.post("/forgot-password")
12 .form([("email", user.email.as_str())])
13 .await
14 .assert_redirect();
15 
16 let emails = mail.queued::<ResetPasswordEmail>();
17 let token = &emails[0].mailable().token;
18 
19 app.post("/reset-password")
20 .form([
21 ("token", token.as_str()),
22 ("email", user.email.as_str()),
23 ("password", "new-password"),
24 ("password_confirmation", "new-password"),
25 ])
26 .await
27 .assert_redirect_to(route!(auth::show_login)?);
28 
29 Ok(())
30}