Authorization
Introduction
While authentication identifies who the current user is, authorization determines which actions they are permitted to perform. For example, in a blog application, any user may read a published post, while only its author may edit or delete it.
Laravel organizes authorization rules into policies. A policy is a set of functions, one for each ability (such as updating or deleting a post), and each function returns an auth.Ability that decides for a given user. Because you call the policy function itself when you check an ability, a misspelled name or a record of the wrong type is caught when your application compiles:
1if err := auth.Authorize(r, policies.UpdatePost(&post)); err != nil {2 return web.Fail(err)3}1if err := auth.Authorize(r, policies.UpdatePost(&post)); err != nil {2 return web.Fail(err)3}
Writing policies
Put your policies in a policies package, and give each model a file of its own. Each function takes the records the decision needs and returns an auth.Ability. The ability is a function that receives the logged-in user and returns nil to allow the action, or a denial to refuse it.
For example, suppose each Post model stores the UserID of its author. This policy, in policies/post.go, allows only the author to update or delete a post:
1package policies23import (4 "go.laravel.com/auth"56 "app/models"7)89func UpdatePost(post *models.Post) auth.Ability[models.User] {10 return func(user *models.User) error {11 return auth.Allow(user.ID == post.UserID)12 }13}1415func DeletePost(post *models.Post) auth.Ability[models.User] {16 return func(user *models.User) error {17 return auth.Allow(user.ID == post.UserID)18 }19}1package policies23import (4 "go.laravel.com/auth"56 "app/models"7)89func UpdatePost(post *models.Post) auth.Ability[models.User] {10 return func(user *models.User) error {11 return auth.Allow(user.ID == post.UserID)12 }13}1415func DeletePost(post *models.Post) auth.Ability[models.User] {16 return func(user *models.User) error {17 return auth.Allow(user.ID == post.UserID)18 }19}
auth.Allow returns nil when its argument is true, and otherwise a denial. There's nothing to register: you import the policies package wherever you check an ability.
Name each function after the action it allows and the model it's about. The usual names are ViewAnyPost, ViewPost, CreatePost, UpdatePost, DeletePost, RestorePost, and ForceDeletePost, but you may add any ability your application needs.
Because a policy is a set of ordinary functions, abilities that make the same check may share an unexported helper in the same file:
1func UpdatePost(post *models.Post) auth.Ability[models.User] {2 return func(user *models.User) error {3 return auth.Allow(ownsPost(user, post))4 }5}67func DeletePost(post *models.Post) auth.Ability[models.User] {8 return func(user *models.User) error {9 return auth.Allow(ownsPost(user, post))10 }11}1213func ownsPost(user *models.User, post *models.Post) bool {14 return user.ID == post.UserID15}1func UpdatePost(post *models.Post) auth.Ability[models.User] {2 return func(user *models.User) error {3 return auth.Allow(ownsPost(user, post))4 }5}67func DeletePost(post *models.Post) auth.Ability[models.User] {8 return func(user *models.User) error {9 return auth.Allow(ownsPost(user, post))10 }11}1213func ownsPost(user *models.User, post *models.Post) bool {14 return user.ID == post.UserID15}
Policy responses
When auth.Allow denies an action, the user gets a 403 status and the default message "This action is unauthorized." To return a custom denial message instead, return auth.Deny with the message, or nil to allow the action:
1func UpdatePost(post *models.Post) auth.Ability[models.User] {2 return func(user *models.User) error {3 if user.ID != post.UserID {4 return auth.Deny("You do not own this post.")5 }67 return nil8 }9}1func UpdatePost(post *models.Post) auth.Ability[models.User] {2 return func(user *models.User) error {3 if user.ID != post.UserID {4 return auth.Deny("You do not own this post.")5 }67 return nil8 }9}
When you want to hide whether a record exists from unauthorized users, such as another team's private project, return auth.DenyAsNotFound(), which responds with a 404 status instead of 403:
1func ViewProject(project *models.Project) auth.Ability[models.User] {2 return func(user *models.User) error {3 if user.TeamID != project.TeamID {4 return auth.DenyAsNotFound()5 }67 return nil8 }9}1func ViewProject(project *models.Project) auth.Ability[models.User] {2 return func(user *models.User) error {3 if user.TeamID != project.TeamID {4 return auth.DenyAsNotFound()5 }67 return nil8 }9}
If you need a different HTTP status code altogether, call auth.DenyWithStatus, which responds with that status code and its standard text, such as "Unauthorized" for a 401:
1return auth.DenyWithStatus(401)1return auth.DenyWithStatus(401)
Abilities without a record
Some abilities don't involve a record yet, such as creating a post. Their functions take no arguments. This one lets users create posts once they've verified their email address:
1func CreatePost() auth.Ability[models.User] {2 return func(user *models.User) error {3 return auth.Allow(user.EmailVerifiedAt != nil)4 }5}1func CreatePost() auth.Ability[models.User] {2 return func(user *models.User) error {3 return auth.Allow(user.EmailVerifiedAt != nil)4 }5}
Abilities that don't involve a specific model, such as viewing an admin dashboard, go in a file of their own, such as policies/admin.go. For example, suppose your users have an IsAdmin field:
1package policies23import (4 "go.laravel.com/auth"56 "app/models"7)89func ViewAdminDashboard() auth.Ability[models.User] {10 return func(user *models.User) error {11 return auth.Allow(user.IsAdmin)12 }13}1package policies23import (4 "go.laravel.com/auth"56 "app/models"7)89func ViewAdminDashboard() auth.Ability[models.User] {10 return func(user *models.User) error {11 return auth.Allow(user.IsAdmin)12 }13}
Guests
By default, Laravel denies guests an auth.Ability without running it, so the ability always receives a user. To decide for guests yourself, return an auth.GuestAbility instead, which receives nil for a visitor who isn't logged in. For example, suppose posts have a Published field, so anyone may view a published post while only its author may view a draft:
1func ViewPost(post *models.Post) auth.GuestAbility[models.User] {2 return func(user *models.User) error {3 return auth.Allow(post.Published || user != nil && user.ID == post.UserID)4 }5}1func ViewPost(post *models.Post) auth.GuestAbility[models.User] {2 return func(user *models.User) error {3 return auth.Allow(post.Published || user != nil && user.ID == post.UserID)4 }5}
Allowing administrators everything
Sometimes you may have administrators who are permitted to perform every action a policy covers. Rather than check IsAdmin in every ability, write a function in the same file that wraps an ability with the check, and wrap each ability that administrators may always perform:
1func orAdmin(ability auth.Ability[models.User]) auth.Ability[models.User] {2 return func(user *models.User) error {3 if user.IsAdmin {4 return nil5 }67 return ability(user)8 }9}1011func UpdatePost(post *models.Post) auth.Ability[models.User] {12 return orAdmin(func(user *models.User) error {13 return auth.Allow(user.ID == post.UserID)14 })15}1func orAdmin(ability auth.Ability[models.User]) auth.Ability[models.User] {2 return func(user *models.User) error {3 if user.IsAdmin {4 return nil5 }67 return ability(user)8 }9}1011func UpdatePost(post *models.Post) auth.Ability[models.User] {12 return orAdmin(func(user *models.User) error {13 return auth.Allow(user.ID == post.UserID)14 })15}
The wrapper runs before the ability it wraps, and decides in one of three ways:
- Returning
nilimmediately grants permission without running the wrapped ability. - Returning a denial, such as
auth.Deny("Your account is suspended.")for a suspended user, immediately denies permission. - Calling the wrapped ability lets it decide for itself.
Because Laravel denies guests before an auth.Ability runs, orAdmin never receives a nil user. An auth.GuestAbility needs a wrapper of its own that checks for nil first.
If administrators may do everything except a few actions, such as permanently deleting posts, leave orAdmin off those abilities:
1func ForceDeletePost(post *models.Post) auth.Ability[models.User] {2 return func(user *models.User) error {3 return auth.Allow(user.ID == post.UserID)4 }5}1func ForceDeletePost(post *models.Post) auth.Ability[models.User] {2 return func(user *models.User) error {3 return auth.Allow(user.ID == post.UserID)4 }5}
Abilities that query the database
When an authorization check needs to query the database, take a context.Context as the policy function's first argument and run the query with it. For example, this policy allows authors to delete a post only while it has no comments:
1package policies23import (4 "context"56 "go.laravel.com/auth"7 "go.laravel.com/model"89 "app/models"10)1112func DeletePost(ctx context.Context, post *models.Post) auth.Ability[models.User] {13 return func(user *models.User) error {14 if user.ID != post.UserID {15 return auth.Deny("You do not own this post.")16 }1718 commented, err := model.Query[models.Comment]().Where("post_id", "=", post.ID).Exists(ctx)19 if err != nil {20 return err21 }2223 if commented {24 return auth.Deny("You can't delete a post with comments.")25 }2627 return nil28 }29}1package policies23import (4 "context"56 "go.laravel.com/auth"7 "go.laravel.com/model"89 "app/models"10)1112func DeletePost(ctx context.Context, post *models.Post) auth.Ability[models.User] {13 return func(user *models.User) error {14 if user.ID != post.UserID {15 return auth.Deny("You do not own this post.")16 }1718 commented, err := model.Query[models.Comment]().Where("post_id", "=", post.ID).Exists(ctx)19 if err != nil {20 return err21 }2223 if commented {24 return auth.Deny("You can't delete a post with comments.")25 }2627 return nil28 }29}
A handler passes r as the context, as in policies.DeletePost(r, &post). If the ability returns an error that isn't a denial, such as from a failed database query, Laravel fails the request with a 500 server error rather than treating it as an authorization denial.
Checking abilities
Once your policy is written, check its abilities in your handlers with auth.Authorize or auth.Can, passing the request and the ability your policy function returns.
In this example, the handlers find the post with model.FromRoute. Only a user who may update the post sees its edit page, and the post's page tells the frontend whether to show a Delete button:
1package posts23import (4 "go.laravel.com/auth"5 "go.laravel.com/inertia"6 "go.laravel.com/model"7 "go.laravel.com/web"89 "app/models"10 "app/policies"11)1213func Edit(r *web.Request) *web.Response {14 post, err := model.FromRoute[models.Post](r, "post")15 if err != nil {16 return web.Fail(err)17 }1819 if err := auth.Authorize(r, policies.UpdatePost(&post)); err != nil {20 return web.Fail(err)21 }2223 return inertia.Render("Posts/Edit", inertia.Props{"post": post})24}2526func Show(r *web.Request) *web.Response {27 post, err := model.FromRoute[models.Post](r, "post")28 if err != nil {29 return web.Fail(err)30 }3132 canDelete, err := auth.Can(r, policies.DeletePost(&post))33 if err != nil {34 return web.Fail(err)35 }3637 return inertia.Render("Posts/Show", inertia.Props{"post": post, "canDelete": canDelete})38}1package posts23import (4 "go.laravel.com/auth"5 "go.laravel.com/inertia"6 "go.laravel.com/model"7 "go.laravel.com/web"89 "app/models"10 "app/policies"11)1213func Edit(r *web.Request) *web.Response {14 post, err := model.FromRoute[models.Post](r, "post")15 if err != nil {16 return web.Fail(err)17 }1819 if err := auth.Authorize(r, policies.UpdatePost(&post)); err != nil {20 return web.Fail(err)21 }2223 return inertia.Render("Posts/Edit", inertia.Props{"post": post})24}2526func Show(r *web.Request) *web.Response {27 post, err := model.FromRoute[models.Post](r, "post")28 if err != nil {29 return web.Fail(err)30 }3132 canDelete, err := auth.Can(r, policies.DeletePost(&post))33 if err != nil {34 return web.Fail(err)35 }3637 return inertia.Render("Posts/Show", inertia.Props{"post": post, "canDelete": canDelete})38}
auth.Authorize returns nil when the user may act and the denial otherwise, so passing its error to web.Fail responds with the denial's status and message. auth.Can returns a bool so you can branch on it yourself, and returns an error only for a failure, such as a failed query, never for a denial.
For abilities that don't take a record, such as CreatePost, call the policy function without arguments:
1func Create(r *web.Request) *web.Response {2 if err := auth.Authorize(r, policies.CreatePost()); err != nil {3 return web.Fail(err)4 }56 return inertia.Render("Posts/Create")7}1func Create(r *web.Request) *web.Response {2 if err := auth.Authorize(r, policies.CreatePost()); err != nil {3 return web.Fail(err)4 }56 return inertia.Render("Posts/Create")7}
Both functions read the user from the context, as auth.User does, so they work the same on routes that guests may visit. A guest gets a 403 from auth.Authorize and false from auth.Can, unless the ability is a GuestAbility. A function your handler calls may also check an ability with the ctx it receives, as in auth.Authorize(ctx, policies.UpdatePost(&post)).
Passing more arguments
A policy function may take as many records as a decision needs. For example, suppose an author may move a post into a Category only if that category is unlocked:
1func MovePost(post *models.Post, category *models.Category) auth.Ability[models.User] {2 return func(user *models.User) error {3 return auth.Allow(user.ID == post.UserID && !category.Locked)4 }5}1func MovePost(post *models.Post, category *models.Category) auth.Ability[models.User] {2 return func(user *models.User) error {3 return auth.Allow(user.ID == post.UserID && !category.Locked)4 }5}
Pass the records in the function's order when you check the ability:
1if err := auth.Authorize(r, policies.MovePost(&post, &category)); err != nil {2 return web.Fail(err)3}1if err := auth.Authorize(r, policies.MovePost(&post, &category)); err != nil {2 return web.Fail(err)3}
Authorizing a form
A form type can authorize the incoming request itself, so every handler that validates the form checks the same ability and doesn't need to call auth.Authorize. Give the form type an Authorize method. When the ability needs a model, such as the post on a /posts/{post} route, find the model from the route and return auth.Authorize's result:
1package posts23import (4 "go.laravel.com/auth"5 "go.laravel.com/model"6 "go.laravel.com/validation"7 "go.laravel.com/validation/rule"8 "go.laravel.com/web"910 "app/models"11 "app/policies"12)1314type UpdatePost struct {15 Title string `json:"title"`16}1718func (UpdatePost) Authorize(r *web.Request) error {19 post, err := model.FromRoute[models.Post](r, "post")20 if err != nil {21 return err22 }2324 return auth.Authorize(r, policies.UpdatePost(&post))25}2627func (f *UpdatePost) Rules() validation.Rules {28 return validation.For(f, rule.Field(&f.Title, rule.Required, rule.Max(255)))29}3031func Update(r *web.Request) *web.Response {32 form, err := r.Validate[UpdatePost]()33 if err != nil {34 return web.Fail(err)35 }3637 // Only users who may update the post get here, with a valid form.Title...3839 return web.Redirect("/posts/" + r.PathValue("post"))40}1package posts23import (4 "go.laravel.com/auth"5 "go.laravel.com/model"6 "go.laravel.com/validation"7 "go.laravel.com/validation/rule"8 "go.laravel.com/web"910 "app/models"11 "app/policies"12)1314type UpdatePost struct {15 Title string `json:"title"`16}1718func (UpdatePost) Authorize(r *web.Request) error {19 post, err := model.FromRoute[models.Post](r, "post")20 if err != nil {21 return err22 }2324 return auth.Authorize(r, policies.UpdatePost(&post))25}2627func (f *UpdatePost) Rules() validation.Rules {28 return validation.For(f, rule.Field(&f.Title, rule.Required, rule.Max(255)))29}3031func Update(r *web.Request) *web.Response {32 form, err := r.Validate[UpdatePost]()33 if err != nil {34 return web.Fail(err)35 }3637 // Only users who may update the post get here, with a valid form.Title...3839 return web.Redirect("/posts/" + r.PathValue("post"))40}
r.Validate calls Authorize for the current user before it validates the input. A user who may not update the post gets the denial's response, not validation errors.
Checking types other than users
An ability may decide for a type other than your user, such as a team whose plan limits how many projects it has. Write the ability with the type in place of the user:
1func CreateProject() auth.Ability[models.Team] {2 return func(team *models.Team) error {3 return auth.Allow(team.ProjectsCount < team.ProjectLimit)4 }5}1func CreateProject() auth.Ability[models.Team] {2 return func(team *models.Team) error {3 return auth.Allow(team.ProjectsCount < team.ProjectLimit)4 }5}
auth.Authorize and auth.Can only check the logged-in user, so to check the team, call the ability with it. The ability returns its denial, which responds with a 403 and its message, such as in a handler for the route /teams/{team}/projects:
1func Store(r *web.Request) *web.Response {2 team, err := model.FromRoute[models.Team](r, "team")3 if err != nil {4 return web.Fail(err)5 }67 if err := policies.CreateProject()(&team); err != nil {8 return web.Fail(err)9 }1011 // ...12}1func Store(r *web.Request) *web.Response {2 team, err := model.FromRoute[models.Team](r, "team")3 if err != nil {4 return web.Fail(err)5 }67 if err := policies.CreateProject()(&team); err != nil {8 return web.Fail(err)9 }1011 // ...12}
You may also call auth.AuthorizeFor(&team, policies.CreateProject()) to get the same denial error (handling a nil subject as a guest), or auth.Allows(&team, policies.CreateProject()) if you'd rather get a bool. Both also check a user other than the logged-in one, such as each member of a team.
Code outside a handler checks the user it receives as an argument by calling the ability with that user, as the handler above calls it with the team. The check then works in a job or a command as well as in a handler:
1func Publish(ctx context.Context, author *models.User, post *models.Post) error {2 if err := policies.UpdatePost(post)(author); err != nil {3 return err4 }56 return model.Update(ctx, post, db.Values{"published_at": date.Now(ctx)})7}1func Publish(ctx context.Context, author *models.User, post *models.Post) error {2 if err := policies.UpdatePost(post)(author); err != nil {3 return err4 }56 return model.Update(ctx, post, db.Values{"published_at": date.Now(ctx)})7}
Sharing abilities with the frontend
Your pages often need to know what the user may do, so they can hide an Edit button from someone who can't edit. Check the abilities on the server and pass the results to your views or Inertia pages.
In views
In a server-rendered view, pass the ability to the can function where the button is. cannot does the opposite. A view can only call the functions you give it, so add your policy functions to ViewFuncs in bootstrap/app.go, as the templates guide's section on users and abilities shows. Then branch on the ability in your template:
1{{if can (updatePost .Post)}}2 <a href="{{route "posts.edit" "post" .Post.ID}}">Edit</a>3{{end}}1{{if can (updatePost .Post)}}2 <a href="{{route "posts.edit" "post" .Post.ID}}">Edit</a>3{{end}}
With Inertia
With Inertia, check the abilities in your handler and pass the results as props:
1func Show(r *web.Request) *web.Response {2 post, err := model.FromRoute[models.Post](r, "post")3 if err != nil {4 return web.Fail(err)5 }67 canUpdate, err := auth.Can(r, policies.UpdatePost(&post))8 if err != nil {9 return web.Fail(err)10 }1112 canDelete, err := auth.Can(r, policies.DeletePost(&post))13 if err != nil {14 return web.Fail(err)15 }1617 return inertia.Render("Posts/Show", inertia.Props{18 "post": post,19 "can": map[string]bool{"update": canUpdate, "delete": canDelete},20 })21}1func Show(r *web.Request) *web.Response {2 post, err := model.FromRoute[models.Post](r, "post")3 if err != nil {4 return web.Fail(err)5 }67 canUpdate, err := auth.Can(r, policies.UpdatePost(&post))8 if err != nil {9 return web.Fail(err)10 }1112 canDelete, err := auth.Can(r, policies.DeletePost(&post))13 if err != nil {14 return web.Fail(err)15 }1617 return inertia.Render("Posts/Show", inertia.Props{18 "post": post,19 "can": map[string]bool{"update": canUpdate, "delete": canDelete},20 })21}
For abilities that every page needs, such as whether the user may create posts, return them from the share function of your Inertia middleware, in bootstrap/app.go. A key with dots adds to the shared auth prop, next to auth.user:
1func share(r *web.Request) (inertia.Props, error) {2 canCreatePosts, err := auth.Can(r, policies.CreatePost())3 if err != nil {4 return nil, err5 }67 return inertia.Props{8 "name": config.From(r).App.Name,9 "auth.user": models.CurrentUser(r),10 "auth.permissions.post.create": canCreatePosts,11 }, nil12}1func share(r *web.Request) (inertia.Props, error) {2 canCreatePosts, err := auth.Can(r, policies.CreatePost())3 if err != nil {4 return nil, err5 }67 return inertia.Props{8 "name": config.From(r).App.Name,9 "auth.user": models.CurrentUser(r),10 "auth.permissions.post.create": canCreatePosts,11 }, nil12}
A hidden button doesn't protect an endpoint, so the handler for the action must still call auth.Authorize.
Testing
To test a handler's authorization, send requests as different users with ActingAs, and check each response. This test expects the UpdatePost ability from policy responses:
1package feature_test23import (4 "strconv"5 "testing"67 "go.laravel.com/model"89 "app/database/factories"10 "app/models"11 "app/tests"12)1314func TestOnlyTheAuthorMayUpdateAPost(t *testing.T) {15 client := tests.New(t)16 author := client.Create(factories.User)17 other := client.Create(factories.User)1819 post := models.Post{UserID: author.ID, Title: "Hello", Published: true}20 if err := model.Create(client.Context(), &post); err != nil {21 t.Fatal(err)22 }2324 path := "/posts/" + strconv.FormatInt(post.ID, 10)2526 client.ActingAs(&other).PutJSON(path, map[string]string{"title": "Goodbye"}).27 AssertForbidden().28 AssertJSONPath("message", "You do not own this post.")2930 client.ActingAs(&author).PutJSON(path, map[string]string{"title": "Goodbye"}).31 AssertRedirect(path)32}1package feature_test23import (4 "strconv"5 "testing"67 "go.laravel.com/model"89 "app/database/factories"10 "app/models"11 "app/tests"12)1314func TestOnlyTheAuthorMayUpdateAPost(t *testing.T) {15 client := tests.New(t)16 author := client.Create(factories.User)17 other := client.Create(factories.User)1819 post := models.Post{UserID: author.ID, Title: "Hello", Published: true}20 if err := model.Create(client.Context(), &post); err != nil {21 t.Fatal(err)22 }2324 path := "/posts/" + strconv.FormatInt(post.ID, 10)2526 client.ActingAs(&other).PutJSON(path, map[string]string{"title": "Goodbye"}).27 AssertForbidden().28 AssertJSONPath("message", "You do not own this post.")2930 client.ActingAs(&author).PutJSON(path, map[string]string{"title": "Goodbye"}).31 AssertRedirect(path)32}
An ability is an ordinary function, so a unit test may also call it directly with records you build in the test, as in policies.UpdatePost(&post)(&user). A wrapper such as orAdmin runs in a direct call too.