Skip to content

Resetting Passwords

Security

Resetting Passwords

Introduction

Laravel includes password reset support for creating and verifying reset tokens, emailing reset links, and updating hashed passwords while leaving the routes and forms under your application's control.

Before getting started, set up authentication so users can log in.

Preparing your application

Laravel sends password reset emails through your mailer, to the address that your User model's MailAddress method returns. Add this method to your User model in models/user.go, as the mail guide's section on recipients describes:

1func (u User) MailAddress() mail.Address {
2 return mail.Address{Name: u.Name, Email: u.Email}
3}
1func (u User) MailAddress() mail.Address {
2 return mail.Address{Name: u.Name, Email: u.Email}
3}

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 routes/web.go, pointing at handlers in a passwords package of your own, behind RedirectIfAuthenticated, which sends a user who is already logged in to their home page instead.

Name the reset form's route password.reset, because the links in reset emails point to it. Each link carries its reset token in the route's {token} parameter, so if the password.reset route lacks that parameter, the application refuses to start:

1import (
2 "go.laravel.com/auth"
3 "go.laravel.com/routing"
4 
5 "app/handlers/passwords"
6)
7 
8route.Middleware(auth.RedirectIfAuthenticated{}).Group(func(route *routing.Router) {
9 route.Get("/forgot-password", passwords.ShowForgotPassword)
10 route.Post("/forgot-password", passwords.SendResetLink)
11 route.Get("/reset-password/{token}", passwords.ShowResetPassword).Name("password.reset")
12 route.Post("/reset-password", passwords.ResetPassword)
13})
1import (
2 "go.laravel.com/auth"
3 "go.laravel.com/routing"
4 
5 "app/handlers/passwords"
6)
7 
8route.Middleware(auth.RedirectIfAuthenticated{}).Group(func(route *routing.Router) {
9 route.Get("/forgot-password", passwords.ShowForgotPassword)
10 route.Post("/forgot-password", passwords.SendResetLink)
11 route.Get("/reset-password/{token}", passwords.ShowResetPassword).Name("password.reset")
12 route.Post("/reset-password", passwords.ResetPassword)
13})

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

1package passwords
2 
3import (
4 "go.laravel.com/auth"
5 "go.laravel.com/inertia"
6 "go.laravel.com/validation"
7 "go.laravel.com/validation/rule"
8 "go.laravel.com/web"
9 
10 "app/models"
11)
12 
13type ForgotPassword struct {
14 Email string `json:"email"`
15}
16 
17func (f *ForgotPassword) Rules() validation.Rules {
18 return validation.For(f, rule.Field(&f.Email, rule.Required, rule.Email))
19}
20 
21func ShowForgotPassword(r *web.Request) *web.Response {
22 return inertia.Render("auth/ForgotPassword")
23}
24 
25func SendResetLink(r *web.Request) *web.Response {
26 form, err := r.Validate[ForgotPassword]()
27 if err != nil {
28 return web.Fail(err)
29 }
30 
31 if err := auth.SendResetLink[models.User](r, form.Email); err != nil {
32 return web.Fail(err)
33 }
34 
35 inertia.Flash(r, "status", "If that email has an account, we've sent it a reset link.")
36 
37 return web.Back()
38}
1package passwords
2 
3import (
4 "go.laravel.com/auth"
5 "go.laravel.com/inertia"
6 "go.laravel.com/validation"
7 "go.laravel.com/validation/rule"
8 "go.laravel.com/web"
9 
10 "app/models"
11)
12 
13type ForgotPassword struct {
14 Email string `json:"email"`
15}
16 
17func (f *ForgotPassword) Rules() validation.Rules {
18 return validation.For(f, rule.Field(&f.Email, rule.Required, rule.Email))
19}
20 
21func ShowForgotPassword(r *web.Request) *web.Response {
22 return inertia.Render("auth/ForgotPassword")
23}
24 
25func SendResetLink(r *web.Request) *web.Response {
26 form, err := r.Validate[ForgotPassword]()
27 if err != nil {
28 return web.Fail(err)
29 }
30 
31 if err := auth.SendResetLink[models.User](r, form.Email); err != nil {
32 return web.Fail(err)
33 }
34 
35 inertia.Flash(r, "status", "If that email has an account, we've sent it a reset link.")
36 
37 return web.Back()
38}

The handler flashes its status with inertia.Flash before it redirects, so the forgot password page receives the message in its flash field. To learn more, check out the Inertia guide's section on flash data.

When no user matches the email, SendResetLink sends nothing and returns nil, 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, SendResetLink skips sending; otherwise, the new link replaces the previous one.

Resetting the password

The link in the email opens your password.reset route. 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 auth.ResetPassword:

1package passwords
2 
3import (
4 "go.laravel.com/auth"
5 "go.laravel.com/hash"
6 "go.laravel.com/inertia"
7 "go.laravel.com/validation"
8 "go.laravel.com/validation/rule"
9 "go.laravel.com/web"
10 
11 "app/models"
12)
13 
14type NewPassword struct {
15 Token string `json:"token"`
16 Email string `json:"email"`
17 Password string `json:"password"`
18}
19 
20func (f *NewPassword) Rules() validation.Rules {
21 return validation.For(f,
22 rule.Field(&f.Token, rule.Required),
23 rule.Field(&f.Email, rule.Required, rule.Email),
24 rule.Field(&f.Password, rule.Required, rule.Min(8), hash.Password, rule.Confirmed),
25 )
26}
27 
28func ShowResetPassword(r *web.Request) *web.Response {
29 return inertia.Render("auth/ResetPassword", inertia.Props{
30 "token": r.PathValue("token"),
31 "email": r.URL.Query().Get("email"),
32 })
33}
34 
35func ResetPassword(r *web.Request) *web.Response {
36 form, err := r.Validate[NewPassword]()
37 if err != nil {
38 return web.Fail(err)
39 }
40 
41 if _, err := auth.ResetPassword[models.User](r, form.Email, form.Token, form.Password); err != nil {
42 return web.Fail(err)
43 }
44 
45 inertia.Flash(r, "status", "Your password has been reset.")
46 
47 return web.RedirectRoute("login")
48}
1package passwords
2 
3import (
4 "go.laravel.com/auth"
5 "go.laravel.com/hash"
6 "go.laravel.com/inertia"
7 "go.laravel.com/validation"
8 "go.laravel.com/validation/rule"
9 "go.laravel.com/web"
10 
11 "app/models"
12)
13 
14type NewPassword struct {
15 Token string `json:"token"`
16 Email string `json:"email"`
17 Password string `json:"password"`
18}
19 
20func (f *NewPassword) Rules() validation.Rules {
21 return validation.For(f,
22 rule.Field(&f.Token, rule.Required),
23 rule.Field(&f.Email, rule.Required, rule.Email),
24 rule.Field(&f.Password, rule.Required, rule.Min(8), hash.Password, rule.Confirmed),
25 )
26}
27 
28func ShowResetPassword(r *web.Request) *web.Response {
29 return inertia.Render("auth/ResetPassword", inertia.Props{
30 "token": r.PathValue("token"),
31 "email": r.URL.Query().Get("email"),
32 })
33}
34 
35func ResetPassword(r *web.Request) *web.Response {
36 form, err := r.Validate[NewPassword]()
37 if err != nil {
38 return web.Fail(err)
39 }
40 
41 if _, err := auth.ResetPassword[models.User](r, form.Email, form.Token, form.Password); err != nil {
42 return web.Fail(err)
43 }
44 
45 inertia.Flash(r, "status", "Your password has been reset.")
46 
47 return web.RedirectRoute("login")
48}

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

ResetPassword 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, ResetPassword 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

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

1func ResetPassword(r *web.Request) *web.Response {
2 form, err := r.Validate[NewPassword]()
3 if err != nil {
4 return web.Fail(err)
5 }
6 
7 user, err := auth.ResetPassword[models.User](r, form.Email, form.Token, form.Password)
8 if err != nil {
9 return web.Fail(err)
10 }
11 
12 if err := auth.Login(r, user, false); err != nil {
13 return web.Fail(err)
14 }
15 
16 return web.RedirectRoute("dashboard")
17}
1func ResetPassword(r *web.Request) *web.Response {
2 form, err := r.Validate[NewPassword]()
3 if err != nil {
4 return web.Fail(err)
5 }
6 
7 user, err := auth.ResetPassword[models.User](r, form.Email, form.Token, form.Password)
8 if err != nil {
9 return web.Fail(err)
10 }
11 
12 if err := auth.Login(r, user, false); err != nil {
13 return web.Fail(err)
14 }
15 
16 return web.RedirectRoute("dashboard")
17}

A user may open an expired or already-used link. To notify them before they enter a new password, call auth.ValidateResetToken in the reset page's handler. It returns the matching user, or nil, without consuming the reset token:

1func ShowResetPassword(r *web.Request) *web.Response {
2 token, email := r.PathValue("token"), r.URL.Query().Get("email")
3 
4 user, err := auth.ValidateResetToken[models.User](r, email, token)
5 if err != nil {
6 return web.Fail(err)
7 }
8 if user == nil {
9 return inertia.Render("auth/ResetLinkExpired")
10 }
11 
12 return inertia.Render("auth/ResetPassword", inertia.Props{"token": token, "email": email})
13}
1func ShowResetPassword(r *web.Request) *web.Response {
2 token, email := r.PathValue("token"), r.URL.Query().Get("email")
3 
4 user, err := auth.ValidateResetToken[models.User](r, email, token)
5 if err != nil {
6 return web.Fail(err)
7 }
8 if user == nil {
9 return inertia.Render("auth/ResetLinkExpired")
10 }
11 
12 return inertia.Render("auth/ResetPassword", inertia.Props{"token": token, "email": email})
13}

Customizing the reset email

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

To customize the email's wording without writing a mailable of your own, run vendor:publish with the auth namespace and the view's name:

1laravel vendor:publish auth reset-password
1laravel vendor:publish auth reset-password

The command copies Laravel's view to resources/views/vendor/auth/reset-password.html. Edit that file to fit your brand, and Laravel renders your copy whenever it sends a reset email. The view receives .URL for the reset link and .Minutes for the expiration window.

To change the subject, or to send a mailable of your own, such as a mails.ResetPassword email that greets the user by name, call auth.SendResetLinkWith in place of SendResetLink. It generates a reset token and passes the user and their reset link to your function, so you can queue the email. Like SendResetLink, it calls your function only when the email belongs to a user who hasn't requested a link within the last minute:

1err := auth.SendResetLinkWith(
2 r,
3 form.Email,
4 func(ctx context.Context, user *models.User, link string) error {
5 return mail.To(user).Queue(ctx, mails.ResetPassword{Name: user.Name, Link: link})
6 },
7)
1err := auth.SendResetLinkWith(
2 r,
3 form.Email,
4 func(ctx context.Context, user *models.User, link string) error {
5 return mail.To(user).Queue(ctx, mails.ResetPassword{Name: user.Name, Link: link})
6 },
7)

Because a reset link allows changing the user's password, keep it out of your logs and unencrypted storage. Queue the email with mail.To(..).Queue(..), which encrypts queued mail, rather than placing the link in a plain queued job.

Testing

To test a password reset, give your application a mail fake, read the reset token from the link in the queued auth.ResetPasswordEmail, and submit the reset form with it:

1package feature_test
2 
3import (
4 "net/url"
5 "strings"
6 "testing"
7 
8 "go.laravel.com/auth"
9 "go.laravel.com/mailtest"
10 
11 "app/database/factories"
12 "app/tests"
13)
14 
15func TestUsersCanResetTheirPassword(t *testing.T) {
16 client := tests.New(t)
17 emails := mailtest.New(client)
18 user := client.Create(factories.User)
19 
20 client.Post("/forgot-password", url.Values{"email": {user.Email}}).AssertRedirect("/")
21 
22 sent := emails.Queued[auth.ResetPasswordEmail]()
23 link, _ := url.Parse(sent[0].Mailable.URL)
24 token := strings.TrimPrefix(link.Path, "/reset-password/")
25 
26 client.Post("/reset-password", url.Values{
27 "token": {token},
28 "email": {user.Email},
29 "password": {"new-password"},
30 "password_confirmation": {"new-password"},
31 }).AssertRedirect("/login")
32}
1package feature_test
2 
3import (
4 "net/url"
5 "strings"
6 "testing"
7 
8 "go.laravel.com/auth"
9 "go.laravel.com/mailtest"
10 
11 "app/database/factories"
12 "app/tests"
13)
14 
15func TestUsersCanResetTheirPassword(t *testing.T) {
16 client := tests.New(t)
17 emails := mailtest.New(client)
18 user := client.Create(factories.User)
19 
20 client.Post("/forgot-password", url.Values{"email": {user.Email}}).AssertRedirect("/")
21 
22 sent := emails.Queued[auth.ResetPasswordEmail]()
23 link, _ := url.Parse(sent[0].Mailable.URL)
24 token := strings.TrimPrefix(link.Path, "/reset-password/")
25 
26 client.Post("/reset-password", url.Values{
27 "token": {token},
28 "email": {user.Email},
29 "password": {"new-password"},
30 "password_confirmation": {"new-password"},
31 }).AssertRedirect("/login")
32}