Authentication
- Introduction
- Setting up
- Logging users in
- Retrieving the logged-in user
- Protecting routes
- Logging out
- Changing a password
- Stateless authentication
- Testing
Introduction
Laravel includes session-based authentication for checking passwords, keeping users logged in with the session and a "remember me" cookie, resetting forgotten passwords, and verifying email addresses. Your application provides the pages and forms. If you'd like users to log in with Google, GitHub, or Microsoft, check out the social login guide.
Authentication works through middleware and a set of user queries. The auth.Session middleware identifies the user for each request from the session cookie on web routes, while the queries load that user from storage, typically your users table. For API clients that send a token instead of a session cookie, you may write a request guard.
Once authentication determines who the user is, authorization decides which actions they may perform.
Setting up
New applications include a User model, a migration for the users table, and the session middleware in bootstrap/app.go, while leaving the login, registration, and logout routes up to your application. The sections below walk through each piece so you can customize them, such as logging users in by username instead of email.
Your user type
Your user is a model with an ID, a Password that holds the password's hash, and a RememberToken. Laravel reads those fields by name. The User model in new applications, in models/user.go, looks like this:
package models
import "time"
type User struct {
ID int64 `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
EmailVerifiedAt *time.Time `json:"email_verified_at"`
Password string `json:"-"`
RememberToken *string `json:"-"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}The json:"-" tags keep the password hash and the remember token out of every page and JSON response that holds a user, so keep them when you add fields of your own.
The users table needs a password column and a nullable remember_token column. The migration in new applications creates both:
package migrations
import (
"context"
"go.laravel.com/schema"
)
func createUsersTable(ctx context.Context) error {
return schema.Create(ctx, "users", func(table *schema.Blueprint) {
table.ID()
table.String("name")
table.String("email").Unique()
table.Timestamp("email_verified_at").Nullable()
table.String("password")
table.RememberToken()
table.Timestamps()
})
}The session middleware
The auth.Session middleware keeps the logged-in user's ID in the session, and loads the user on each request. It needs the session, so append it to the web group, after StartSession. New applications do this in bootstrap/app.go:
import (
laravel "go.laravel.com"
"go.laravel.com/auth"
"go.laravel.com/config"
"app/models"
)
Middleware: func(m *laravel.Middleware, cfg *config.Config) {
m.Web.Append(auth.Session[models.User]{})
},The type parameter names your user type. Without other settings, auth.Session finds users in that model's table, and users log in with their email address. To log them in by another column, such as a username, set Username:
m.Web.Append(auth.Session[models.User]{Username: "username"})If you need to keep specific accounts out of your application, such as suspended users, you may find users yourself or check their account status during login.
An application has one auth.Session middleware, for one user type. For roles such as administrators, store the role on your User model and check it in an ability.
Finding users yourself
Laravel finds the user who logs in, loads the logged-in user on each request, and stores new passwords with auth.ModelUsers, which reads and writes your user model's table. If you need to customize those queries, such as to keep suspended accounts from logging in, write a type that embeds auth.ModelUsers and replaces the methods you need. For example, if your users table has a nullable suspended_at column, this type in models/users.go excludes suspended accounts:
package models
import (
"context"
"go.laravel.com/auth"
"go.laravel.com/model"
)
type Users struct {
auth.ModelUsers[User]
}
func (Users) Find(ctx context.Context, id string) (*User, error) {
user, err := model.Query[User]().WhereNull("suspended_at").Find(ctx, id)
return auth.Found(&user, err)
}
func (Users) FindForLogin(ctx context.Context, email string) (*User, error) {
user, err := model.Query[User]().WhereNull("suspended_at").Where("email", "=", email).First(ctx)
return auth.Found(&user, err)
}Then register the type in bootstrap/app.go with your user type as the type parameter:
Users: []laravel.UserProvider{laravel.Users[models.User](models.Users{})},Laravel then uses your type everywhere it finds users: logins through auth.Session, routes authenticated by a request guard, password resets, and email verification. A suspended user who was already logged in is logged out on their next request.
Naming pages
Laravel needs to know which routes serve a few core authentication pages, so it can redirect guests to your login form and build password reset and email verification links. Laravel finds each of these pages by its route name, so give the routes your application has these names:
| Route name | Page | Who sends users there |
|---|---|---|
login | The login page | Authenticate, for guests |
dashboard, or else home | The logged-in user's home | RedirectIfAuthenticated, for logged-in users |
password.reset | The form that sets a new password | The link in password reset emails |
verification.notice | The page that asks the user to verify their email | RequireVerifiedEmail |
verification.verify | The handler that verifies the email | The link in verification emails |
For example, this route in routes/web.go names your login page:
route.Get("/login", sessions.Create).Name("login")You don't need to name every page, only the ones your application has. For example, leave out verification.notice and verification.verify if your users don't verify their email. The links in Laravel's emails fill some parameters of their routes, so the password.reset route needs a {token} parameter, and the verification.verify route needs {id} and {hash}.
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, validate the form and pass the email and password to auth.Attempt. It finds the user, checks the password, and logs them in:
package sessions
import (
"go.laravel.com/auth"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
)
type Login struct {
Email string `json:"email" transform:"lowercase"`
Password string `json:"password"`
Remember bool `json:"remember"`
}
func (f *Login) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Email, rule.Required, rule.Email),
rule.Field(&f.Password, rule.Required),
)
}
func Store(r *web.Request) *web.Response {
form, err := r.Validate[Login]()
if err != nil {
return web.Fail(err)
}
if err := auth.Attempt(r, form.Email, form.Password, form.Remember); err != nil {
return web.Fail(err)
}
return auth.RedirectIntendedRoute("dashboard")
}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 you set Username on auth.Session, the error goes on that field instead, so give the form field the same name.
If your login page also has a registration form, validate the login form with r.ValidateIn[Login]("login") instead of r.Validate. The credentials error then goes in the login error bag with the form's other errors, so a view reads it with {{error "email" "login"}}. To learn more, check out the validation guide's section on pages with several forms.
On success, Attempt gives the session a new ID and stores the user in it. auth.RedirectIntendedRoute sends the user to the page they tried to visit before Authenticate sent them to log in, or else to the named route you give it (auth.RedirectIntended falls back to a path string instead).
Laravel hashes passwords with bcrypt. When you raise BCRYPT_ROUNDS, Attempt hashes the user's password again with the new rounds the next time they log in, 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, check the rate limit before calling auth.Attempt and call rate.Hit only on failure:
package sessions
import (
"errors"
"strings"
"go.laravel.com/auth"
"go.laravel.com/rate"
"go.laravel.com/web"
)
func Store(r *web.Request) *web.Response {
form, err := r.Validate[Login]()
if err != nil {
return web.Fail(err)
}
limit := rate.PerMinute(5)
key := "login:" + strings.ToLower(form.Email) + "|" + r.IP()
if _, err := rate.Check(r, key, limit); err != nil {
if tooMany, ok := errors.AsType[*rate.TooManyAttemptsError](err); ok {
return web.Fail(tooMany.On("email", "Too many login attempts. Please try again later."))
}
return web.Fail(err)
}
if err := auth.Attempt(r, form.Email, form.Password, form.Remember); err != nil {
_, _ = rate.Hit(r, key, limit)
return web.Fail(err)
}
_ = rate.Clear(r, key)
return auth.RedirectIntendedRoute("dashboard")
}Remembering users
Many applications show a "remember me" checkbox on their login form. Pass the checkbox's value to Attempt as its last argument:
if err := auth.Attempt(r, form.Email, form.Password, form.Remember); err != nil {
return web.Fail(err)
}A remembered user gets an encrypted cookie, remember_web, that lasts 400 days. After their session expires, the cookie logs them in again 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 auth.Login. The last argument says whether to remember them:
package registrations
import (
"go.laravel.com/auth"
"go.laravel.com/hash"
"go.laravel.com/model"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
"app/models"
)
type SignUp struct {
Name string `json:"name"`
Email string `json:"email" transform:"lowercase"`
Password string `json:"password"`
}
func (f *SignUp) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Name, rule.Required, rule.Max(255)),
rule.Field(&f.Email, rule.Required, rule.Email, model.Unique[models.User]()),
rule.Field(&f.Password, rule.Required, rule.Min(8), hash.Password, rule.Confirmed),
)
}
func Store(r *web.Request) *web.Response {
form, err := r.Validate[SignUp]()
if err != nil {
return web.Fail(err)
}
hashed, err := hash.Make(r, form.Password)
if err != nil {
return web.Fail(err)
}
user := models.User{Name: form.Name, Email: form.Email, Password: hashed}
if err := model.Create(r, &user); err != nil {
return web.Fail(err)
}
if err := auth.Login(r, &user, false); err != nil {
return web.Fail(err)
}
return web.RedirectRoute("dashboard")
}Hash the password before you store it, so the plain text never reaches your database. The hash.Password rule fails validation for a password too long to hash, so the user sees an error on the password field instead of an error page.
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 model.Unique and auth.Attempt run. To learn more, check out the validation guide's section on transforming input fields.
Handling a failed login yourself
Attempt calls auth.Validate, then auth.Login. When you'd like to decide what a failed login does, call both functions yourself. Validate returns the user whose email and password match, without logging them in, or nil.
For example, say your users table has a nullable suspended_at column, which your User holds in a SuspendedAt *time.Time field. This handler, for the Login form above, logs failed attempts and tells suspended users why they can't log in:
import (
"log/slog"
"go.laravel.com/auth"
"go.laravel.com/web"
"app/models"
)
func Store(r *web.Request) *web.Response {
form, err := r.Validate[Login]()
if err != nil {
return web.Fail(err)
}
user, err := auth.Validate[models.User](r, form.Email, form.Password)
if err != nil {
return web.Fail(err)
}
if user == nil {
slog.InfoContext(r, "failed login", "email", form.Email)
return web.Invalid("email", "These credentials do not match our records.")
}
if user.SuspendedAt != nil {
return web.Invalid("email", "This account has been suspended.")
}
if err := auth.Login(r, user, form.Remember); err != nil {
return web.Fail(err)
}
return auth.RedirectIntended("/dashboard")
}Retrieving the logged-in user
In a handler, call r.User with your user type to retrieve the logged-in user, or nil for a guest:
package dashboard
import (
"go.laravel.com/inertia"
"go.laravel.com/web"
"app/models"
)
func Show(r *web.Request) *web.Response {
user := r.User[models.User]()
return inertia.Render("Dashboard", inertia.Props{"name": user.Name})
}On a route that Authenticate protects, the user is never nil. The session middleware loads the user once, before your handler runs, so r.User returns no error, and every call during the request shares that one lookup.
Code below the handler reads the user from its ctx with auth.User, so it doesn't need the user as an argument. On pages that guests can see too, check for nil:
package dashboard
import (
"context"
"go.laravel.com/auth"
"app/models"
)
func greeting(ctx context.Context) string {
if user := auth.User[models.User](ctx); user != nil {
return "Welcome back, " + user.Name
}
return "Welcome"
}A handler would call greeting(r). The same call works in a listener, where auth.User returns the user who dispatched the event. New applications wrap auth.User in models.CurrentUser, in models/user.go, so code that reads the user doesn't repeat the type in brackets:
func CurrentUser(ctx context.Context) *User {
return auth.User[User](ctx)
}When you only need to know whether someone is logged in, without the user, call auth.Check. auth.ID returns the logged-in user's ID as text, or "" for a guest:
if auth.Check(r) {
// The user is logged in...
}
if id := auth.ID(r); id != "" {
// ...
}Both take the context too, so they work in middleware and in the code your handlers call.
Your pages' layout usually shows the user too, such as in a navigation bar. You may share the logged-in user with every Inertia page from the share function in bootstrap/app.go, as the auth.user prop, so each handler doesn't pass it in. To learn more, check out the Inertia guide's section on shared data. In a view, the user function returns the logged-in user, as the templates guide's section on users and abilities describes.
A queued job, a command, and a scheduled task have no logged-in user, so auth.User panics there. Give a job the user it acts for in a model field instead. If the job runs code that reads the logged-in user from its context, such as a listener that records who published a post, log the user in with auth.WithUser. It returns a copy of the context in which the user is logged in, so auth.User, auth.Check, and auth.Authorize work as they do in a request:
package jobs
import (
"context"
"go.laravel.com/auth"
"app/models"
"app/posts"
)
type PublishPost struct {
Author models.User `queue:"model"`
Post models.Post `queue:"model"`
}
func (j PublishPost) Handle(ctx context.Context) error {
ctx = auth.WithUser(ctx, &j.Author)
return posts.Publish(ctx, &j.Author, &j.Post)
}Here app/posts stands for a package of your own that takes the author as an argument.
Protecting routes
The auth.Authenticate middleware lets only logged-in users through. Attach it to a group of routes in your route file:
package routes
import (
"go.laravel.com/auth"
"go.laravel.com/config"
"go.laravel.com/routing"
"app/handlers/dashboard"
"app/handlers/settings"
)
func Web(route *routing.Router, cfg *config.Config) {
route.Middleware(auth.Authenticate{}).Group(func(route *routing.Router) {
route.Get("/dashboard", dashboard.Show).Name("dashboard")
route.Get("/settings", settings.Show)
})
}Redirecting guests
Authenticate sends a guest to the route named login. If the guest was visiting a page with GET, Authenticate stores that page's URL in the session, so auth.RedirectIntended can send them there once they log in. A request that expects JSON, or an application without a login route, gets a 401 instead.
A handler or a form may also send a guest to the login page by failing with auth.ErrUnauthenticated.
Pages for guests only
The auth.RedirectIfAuthenticated middleware sends logged-in users to the route named dashboard, or else home, or else /. Use it for pages that only guests need, such as the login page:
route.Middleware(auth.RedirectIfAuthenticated{}).Group(func(route *routing.Router) {
route.Get("/login", sessions.Create).Name("login")
route.Post("/login", sessions.Store)
})Logging out
To log the user out, call auth.Logout. It removes the session's data, gives the session a new ID and CSRF token, and logs out the user's "remember me" cookies on every device:
import (
"go.laravel.com/auth"
"go.laravel.com/inertia"
"go.laravel.com/web"
)
func Destroy(r *web.Request) *web.Response {
if err := auth.Logout(r); err != nil {
return web.Fail(err)
}
inertia.ClearHistory(r)
return web.Redirect("/")
}After a logout, the browser's back button can still show pages the user saw while logged in. With Inertia, turn on history encryption in inertia.Middleware in bootstrap/app.go, and call inertia.ClearHistory when the user logs out, as above. The back button then can't restore those pages:
m.Web.Append(inertia.Middleware{
Share: share,
ErrorPage: "Error",
EncryptHistory: true,
})Logging out other devices
A user who stayed logged in on a shared computer may want to log out there from their own device. To log the user out of their other sessions without logging out the device they're on, confirm their current password and pass it to auth.UpdatePassword:
import (
"go.laravel.com/auth"
"go.laravel.com/inertia"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
)
type LogoutOtherDevices struct {
Password string `json:"password"`
}
func (f *LogoutOtherDevices) Rules() validation.Rules {
return validation.For(f, rule.Field(&f.Password, rule.Required, auth.CurrentPassword))
}
func LogoutOthers(r *web.Request) *web.Response {
form, err := r.Validate[LogoutOtherDevices]()
if err != nil {
return web.Fail(err)
}
if err := auth.UpdatePassword(r, form.Password); err != nil {
return web.Fail(err)
}
inertia.Flash(r, "status", "You're logged out on your other devices.")
return web.Back()
}The auth.CurrentPassword rule rejects the form when the field doesn't match the logged-in user's password.
Under the hood, Laravel stores a signed fingerprint of the user's password hash in each session and "remember me" cookie, and checks it on every request. Bcrypt makes a new random salt each time it hashes a password, so UpdatePassword stores a different hash even for the same password. Laravel gives the current device the new fingerprint, so it stays logged in, while every other device's session and "remember me" cookie fails the check on its next request and is logged out.
Changing a password
To change the logged-in user's password, call auth.UpdatePassword. 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:
import (
"go.laravel.com/auth"
"go.laravel.com/hash"
"go.laravel.com/inertia"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
)
type UpdatePassword struct {
CurrentPassword string `json:"current_password"`
Password string `json:"password"`
}
func (UpdatePassword) Authorize(r *web.Request) error {
return auth.Authenticated(r)
}
func (f *UpdatePassword) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.CurrentPassword, rule.Required, auth.CurrentPassword),
rule.Field(&f.Password, rule.Required, rule.Min(8), hash.Password, rule.Confirmed),
)
}
func Update(r *web.Request) *web.Response {
form, err := r.Validate[UpdatePassword]()
if err != nil {
return web.Fail(err)
}
if err := auth.UpdatePassword(r, form.Password); err != nil {
return web.Fail(err)
}
inertia.Flash(r, "status", "Password updated.")
return web.Back()
}The form's Authorize method sends a guest to the login page before the form is validated, and hash.Password keeps passwords within what bcrypt reads.
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 command.
Stateless authentication
API clients, such as mobile apps or other servers, usually authenticate each request with a bearer token, an API key header, or a signed credential instead of a session cookie. To authenticate these stateless requests, write a request guard. A request guard is a function that inspects the incoming request and returns the matching user, or nil when the request can't be authenticated.
Store a hash of each API token rather than the API token itself, so a leaked database doesn't leak working tokens. A SHA-256 hash is enough for a long random token, and unlike a bcrypt hash, the database can look a row up by it. For example, say your users table has an api_token column that holds the SHA-256 hash. This guard, in handlers/apitokens/apitokens.go, reads the API token from the Authorization: Bearer header:
package apitokens
import (
"crypto/sha256"
"encoding/hex"
"go.laravel.com/auth"
"go.laravel.com/model"
"go.laravel.com/web"
"app/models"
)
func User(r *web.Request) (*models.User, error) {
token := r.BearerToken()
if token == "" {
return nil, nil
}
sum := sha256.Sum256([]byte(token))
user, err := model.Query[models.User]().Where("api_token", "=", hex.EncodeToString(sum[:])).First(r)
return auth.Found(&user, err)
}To protect routes with the guard, use auth.Via, which runs it for each request:
func API(route *routing.Router, cfg *config.Config) {
route.Middleware(auth.Via(apitokens.User)).Get("/me", users.Me)
}If the guard returns nil, the request gets what Authenticate gives a guest: a 401 on an API route. Otherwise, r.User, auth.Can, and the other functions return the guard's user in your handlers:
func Me(r *web.Request) *web.Response {
return web.JSON(r.User[models.User]())
}A request guard needs no session, so it works on routes in the api group. Because there's no session there, Attempt, Login, Logout, and UpdatePassword return an error on those routes.
Testing
To send a test request as a logged-in user, use ActingAs on the test client:
package feature_test
import (
"testing"
"app/database/factories"
"app/tests"
)
func TestTheDashboardGreetsTheUser(t *testing.T) {
client := tests.New(t)
user := client.Create(factories.User)
client.ActingAs(&user).Get("/dashboard").AssertOK().AssertSee("Hello, " + user.Name)
}ActingAs works on routes that a request guard protects too, without running the guard.
The User factory in new applications creates a user whose password is password. To test logging in itself, create a user with the factory and post their credentials to your login route. The client keeps the response's cookies, and with them the session, for its next request:
import "net/url"
func TestUsersCanLogIn(t *testing.T) {
client := tests.New(t)
user := client.Create(factories.User)
client.Post("/login", url.Values{"email": {user.Email}, "password": {"password"}}).
AssertRedirect("/dashboard").
AssertAuthenticatedAs(&user)
client.Get("/dashboard").AssertOK()
}AssertAuthenticated checks that the session has a logged-in user once the request has finished, AssertAuthenticatedAs(&user) checks which user, and AssertGuest checks that it has none, such as after a failed login. To check that a login remembered the user, use AssertCookiePresent("remember_web").
说明
The authentication assertions read the session, and ActingAs logs its user in without it. A request sent with ActingAs counts as a guest in these assertions unless the handler logs a user in.