跳至正文

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:

go
if err := auth.Authorize(r, policies.UpdatePost(&post)); err != nil {
	return web.Fail(err)
}

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:

go
package policies

import (
	"go.laravel.com/auth"

	"app/models"
)

func UpdatePost(post *models.Post) auth.Ability[models.User] {
	return func(user *models.User) error {
		return auth.Allow(user.ID == post.UserID)
	}
}

func DeletePost(post *models.Post) auth.Ability[models.User] {
	return func(user *models.User) error {
		return auth.Allow(user.ID == post.UserID)
	}
}

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:

go
func UpdatePost(post *models.Post) auth.Ability[models.User] {
	return func(user *models.User) error {
		return auth.Allow(ownsPost(user, post))
	}
}

func DeletePost(post *models.Post) auth.Ability[models.User] {
	return func(user *models.User) error {
		return auth.Allow(ownsPost(user, post))
	}
}

func ownsPost(user *models.User, post *models.Post) bool {
	return user.ID == post.UserID
}

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:

go
func UpdatePost(post *models.Post) auth.Ability[models.User] {
	return func(user *models.User) error {
		if user.ID != post.UserID {
			return auth.Deny("You do not own this post.")
		}

		return nil
	}
}

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:

go
func ViewProject(project *models.Project) auth.Ability[models.User] {
	return func(user *models.User) error {
		if user.TeamID != project.TeamID {
			return auth.DenyAsNotFound()
		}

		return nil
	}
}

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:

go
return 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:

go
func CreatePost() auth.Ability[models.User] {
	return func(user *models.User) error {
		return auth.Allow(user.EmailVerifiedAt != nil)
	}
}

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:

go
package policies

import (
	"go.laravel.com/auth"

	"app/models"
)

func ViewAdminDashboard() auth.Ability[models.User] {
	return func(user *models.User) error {
		return auth.Allow(user.IsAdmin)
	}
}

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:

go
func ViewPost(post *models.Post) auth.GuestAbility[models.User] {
	return func(user *models.User) error {
		return auth.Allow(post.Published || user != nil && user.ID == post.UserID)
	}
}

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:

go
func orAdmin(ability auth.Ability[models.User]) auth.Ability[models.User] {
	return func(user *models.User) error {
		if user.IsAdmin {
			return nil
		}

		return ability(user)
	}
}

func UpdatePost(post *models.Post) auth.Ability[models.User] {
	return orAdmin(func(user *models.User) error {
		return auth.Allow(user.ID == post.UserID)
	})
}

The wrapper runs before the ability it wraps, and decides in one of three ways:

  • Returning nil immediately 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:

go
func ForceDeletePost(post *models.Post) auth.Ability[models.User] {
	return func(user *models.User) error {
		return auth.Allow(user.ID == post.UserID)
	}
}

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:

go
package policies

import (
	"context"

	"go.laravel.com/auth"
	"go.laravel.com/model"

	"app/models"
)

func DeletePost(ctx context.Context, post *models.Post) auth.Ability[models.User] {
	return func(user *models.User) error {
		if user.ID != post.UserID {
			return auth.Deny("You do not own this post.")
		}

		commented, err := model.Query[models.Comment]().Where("post_id", "=", post.ID).Exists(ctx)
		if err != nil {
			return err
		}

		if commented {
			return auth.Deny("You can't delete a post with comments.")
		}

		return nil
	}
}

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:

go
package posts

import (
	"go.laravel.com/auth"
	"go.laravel.com/inertia"
	"go.laravel.com/model"
	"go.laravel.com/web"

	"app/models"
	"app/policies"
)

func Edit(r *web.Request) *web.Response {
	post, err := model.FromRoute[models.Post](r, "post")
	if err != nil {
		return web.Fail(err)
	}

	if err := auth.Authorize(r, policies.UpdatePost(&post)); err != nil {
		return web.Fail(err)
	}

	return inertia.Render("Posts/Edit", inertia.Props{"post": post})
}

func Show(r *web.Request) *web.Response {
	post, err := model.FromRoute[models.Post](r, "post")
	if err != nil {
		return web.Fail(err)
	}

	canDelete, err := auth.Can(r, policies.DeletePost(&post))
	if err != nil {
		return web.Fail(err)
	}

	return inertia.Render("Posts/Show", inertia.Props{"post": post, "canDelete": canDelete})
}

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:

go
func Create(r *web.Request) *web.Response {
	if err := auth.Authorize(r, policies.CreatePost()); err != nil {
		return web.Fail(err)
	}

	return inertia.Render("Posts/Create")
}

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:

go
func MovePost(post *models.Post, category *models.Category) auth.Ability[models.User] {
	return func(user *models.User) error {
		return auth.Allow(user.ID == post.UserID && !category.Locked)
	}
}

Pass the records in the function's order when you check the ability:

go
if err := auth.Authorize(r, policies.MovePost(&post, &category)); err != nil {
	return web.Fail(err)
}

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:

go
package posts

import (
	"go.laravel.com/auth"
	"go.laravel.com/model"
	"go.laravel.com/validation"
	"go.laravel.com/validation/rule"
	"go.laravel.com/web"

	"app/models"
	"app/policies"
)

type UpdatePost struct {
	Title string `json:"title"`
}

func (UpdatePost) Authorize(r *web.Request) error {
	post, err := model.FromRoute[models.Post](r, "post")
	if err != nil {
		return err
	}

	return auth.Authorize(r, policies.UpdatePost(&post))
}

func (f *UpdatePost) Rules() validation.Rules {
	return validation.For(f, rule.Field(&f.Title, rule.Required, rule.Max(255)))
}

func Update(r *web.Request) *web.Response {
	form, err := r.Validate[UpdatePost]()
	if err != nil {
		return web.Fail(err)
	}

	// Only users who may update the post get here, with a valid form.Title...

	return web.Redirect("/posts/" + r.PathValue("post"))
}

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:

go
func CreateProject() auth.Ability[models.Team] {
	return func(team *models.Team) error {
		return auth.Allow(team.ProjectsCount < team.ProjectLimit)
	}
}

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:

go
func Store(r *web.Request) *web.Response {
	team, err := model.FromRoute[models.Team](r, "team")
	if err != nil {
		return web.Fail(err)
	}

	if err := policies.CreateProject()(&team); err != nil {
		return web.Fail(err)
	}

	// ...
}

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:

go
func Publish(ctx context.Context, author *models.User, post *models.Post) error {
	if err := policies.UpdatePost(post)(author); err != nil {
		return err
	}

	return model.Update(ctx, post, db.Values{"published_at": date.Now(ctx)})
}

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:

html
{{if can (updatePost .Post)}}
    <a href="{{route "posts.edit" "post" .Post.ID}}">Edit</a>
{{end}}

With Inertia ​

With Inertia, check the abilities in your handler and pass the results as props:

go
func Show(r *web.Request) *web.Response {
	post, err := model.FromRoute[models.Post](r, "post")
	if err != nil {
		return web.Fail(err)
	}

	canUpdate, err := auth.Can(r, policies.UpdatePost(&post))
	if err != nil {
		return web.Fail(err)
	}

	canDelete, err := auth.Can(r, policies.DeletePost(&post))
	if err != nil {
		return web.Fail(err)
	}

	return inertia.Render("Posts/Show", inertia.Props{
		"post": post,
		"can":  map[string]bool{"update": canUpdate, "delete": canDelete},
	})
}

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:

go
func share(r *web.Request) (inertia.Props, error) {
	canCreatePosts, err := auth.Can(r, policies.CreatePost())
	if err != nil {
		return nil, err
	}

	return inertia.Props{
		"name":                         config.From(r).App.Name,
		"auth.user":                    models.CurrentUser(r),
		"auth.permissions.post.create": canCreatePosts,
	}, nil
}

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:

go
package feature_test

import (
	"strconv"
	"testing"

	"go.laravel.com/model"

	"app/database/factories"
	"app/models"
	"app/tests"
)

func TestOnlyTheAuthorMayUpdateAPost(t *testing.T) {
	client := tests.New(t)
	author := client.Create(factories.User)
	other := client.Create(factories.User)

	post := models.Post{UserID: author.ID, Title: "Hello", Published: true}
	if err := model.Create(client.Context(), &post); err != nil {
		t.Fatal(err)
	}

	path := "/posts/" + strconv.FormatInt(post.ID, 10)

	client.ActingAs(&other).PutJSON(path, map[string]string{"title": "Goodbye"}).
		AssertForbidden().
		AssertJSONPath("message", "You do not own this post.")

	client.ActingAs(&author).PutJSON(path, map[string]string{"title": "Goodbye"}).
		AssertRedirect(path)
}

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.