Authorization
Introduction
authentication이 현재 사용자를 식별한다면 인가는 허용된 동작을 결정합니다. 블로그에서는 누구나 발행된 글을 읽지만 작성자만 편집·삭제할 수 있는 것이 예입니다.
Laravel은 인가 규칙을 폴리시로 구성합니다. 폴리시는 게시물 갱신·삭제 같은 능력별 함수 집합이며 각 함수는 주어진 사용자의 권한을 결정하는 auth.Ability를 반환합니다. 검사 시 함수를 직접 호출하므로 이름 오타나 잘못된 레코드 타입을 컴파일할 때 찾습니다.
if err := auth.Authorize(r, policies.UpdatePost(&post)); err != nil {
return web.Fail(err)
}
Writing policies
policies 패키지에 모델마다 파일을 두세요. 각 함수는 판단에 필요한 레코드를 받고 auth.Ability를 반환합니다. 이 능력 함수는 로그인한 사용자를 받아 허용 시 nil, 거부 시 거부 결과를 반환합니다.
각 Post가 작성자의 UserID를 저장한다면 policies/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는 인수가 참이면 nil, 아니면 거부를 반환합니다. 등록은 필요 없으며 검사할 곳에서 policies를 임포트하면 됩니다.
함수 이름은 허용 동작과 모델에 맞추세요. 보통 ViewAnyPost, ViewPost, CreatePost, UpdatePost, DeletePost, RestorePost, ForceDeletePost를 쓰며 필요한 능력을 추가할 수 있습니다.
일반 함수 집합이므로 같은 검사를 하는 능력은 같은 파일의 비공개 헬퍼를 공유할 수 있습니다.
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
auth.Allow가 거부하면 403과 기본 메시지 "This action is unauthorized."를 반환합니다. 사용자 정의 메시지는 auth.Deny에 전달하고 허용할 때는 nil을 반환하세요.
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
}
}
다른 팀의 비공개 프로젝트처럼 존재 여부도 숨기려면 auth.DenyAsNotFound()로 403 대신 404를 반환하세요.
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
}
}
다른 상태 코드가 필요하면 auth.DenyWithStatus를 호출하세요. 401의 "Unauthorized"처럼 해당 코드와 표준 텍스트를 반환합니다.
return auth.DenyWithStatus(401)
Abilities without a record
글 생성처럼 아직 레코드가 없는 능력은 인수를 받지 않습니다. 다음은 이메일을 인증한 사용자에게 글 생성을 허용합니다.
func CreatePost() auth.Ability[models.User] {
return func(user *models.User) error {
return auth.Allow(user.EmailVerifiedAt != nil)
}
}
관리자 대시보드처럼 특정 모델과 무관한 능력은 policies/admin.go 같은 파일에 둡니다. 사용자에게 IsAdmin 필드가 있다고 가정한 예입니다.
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
기본적으로 Laravel은 능력을 실행하기 전에 비로그인 사용자를 거부하므로 auth.Ability는 항상 사용자를 받습니다. 직접 판단하려면 비로그인 방문자에게 nil을 받는 auth.GuestAbility를 반환하세요. Published 필드로 공개 글은 누구나, 초안은 작성자만 보게 하는 예입니다.
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
관리자에게 폴리시의 모든 동작을 허용할 때는 능력마다 IsAdmin을 검사하는 대신 같은 파일에 검사를 추가하는 래퍼 함수를 만들고 항상 허용할 능력을 감싸세요.
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)
})
}
래퍼는 능력보다 먼저 실행되며 세 가지 방식으로 판단합니다.
nil을 반환하면 능력을 실행하지 않고 즉시 허용합니다.- 정지 사용자에
auth.Deny("Your account is suspended.")같은 거부를 반환하면 즉시 거부합니다. - 감싼 능력을 호출하면 능력 자체가 판단합니다.
auth.Ability 실행 전에 비로그인 사용자를 거부하므로 orAdmin은 nil을 받지 않습니다. auth.GuestAbility에는 먼저 nil을 검사하는 별도 래퍼가 필요합니다.
영구 삭제 같은 일부 동작을 관리자도 제한하려면 해당 능력에는 orAdmin을 붙이지 마세요.
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
인가에 조회가 필요하면 폴리시의 첫 인수로 context.Context를 받아 사용하세요. 다음 폴리시는 댓글이 없을 때만 작성자에게 삭제를 허용합니다.
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
}
}
핸들러는 policies.DeletePost(r, &post)처럼 r을 전달합니다. 조회 실패 등 거부 이외의 오류가 반환되면 Laravel은 인가 거부 대신 500 서버 오류로 요청을 실패시킵니다.
Checking abilities
폴리시 작성 후 핸들러에서 요청과 반환된 능력을 auth.Authorize나 auth.Can에 전달하여 검사하세요.
다음 핸들러는 model.FromRoute로 게시물을 찾습니다. 갱신 가능한 사용자만 편집 페이지를 보며, 게시물 페이지는 삭제 버튼 표시 여부를 프런트엔드에 알립니다.
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는 허용 시 nil, 아니면 거부를 반환하므로 오류를 web.Fail에 전달하면 denial's status and message로 응답합니다. auth.Can은 분기용 bool을 반환하며 거부가 아닌 조회 실패 같은 문제에만 오류를 반환합니다.
CreatePost처럼 레코드를 받지 않으면 인수 없이 호출하세요.
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")
}
두 함수는 auth.User처럼 컨텍스트에서 사용자를 읽어 비로그인 접근 라우트에서도 동작합니다. GuestAbility가 아니면 비로그인 사용자에게 auth.Authorize는 403, auth.Can은 false를 반환합니다. 핸들러가 호출한 함수도 받은 ctx로 auth.Authorize(ctx, policies.UpdatePost(&post))처럼 검사할 수 있습니다.
Passing more arguments
폴리시는 판단에 필요한 만큼 레코드를 받을 수 있습니다. 다음은 Category가 잠겨 있지 않을 때만 작성자가 글을 이동할 수 있는 예입니다.
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)
}
}
능력 검사 시 함수 순서대로 레코드를 전달하세요.
if err := auth.Authorize(r, policies.MovePost(&post, &category)); err != nil {
return web.Fail(err)
}
Authorizing a form
form type이 직접 인가하면 모든 유효성 검증 핸들러가 같은 능력을 검사하며 auth.Authorize 호출이 필요 없습니다. 폼 타입에 Authorize를 추가하세요. /posts/{post}의 게시물처럼 모델이 필요하면 라우트에서 찾고 auth.Authorize 결과를 반환하세요.
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는 입력 검증 전 현재 사용자의 Authorize를 호출합니다. 갱신 권한이 없으면 유효성 검증 오류 대신 거부 응답을 받습니다.
Checking types other than users
플랜으로 프로젝트 수를 제한하는 팀처럼 사용자 외의 타입도 판단할 수 있습니다. 사용자 자리에 해당 타입을 쓰세요.
func CreateProject() auth.Ability[models.Team] {
return func(team *models.Team) error {
return auth.Allow(team.ProjectsCount < team.ProjectLimit)
}
}
auth.Authorize와 auth.Can은 로그인 사용자만 검사하므로 팀은 능력에 직접 전달하세요. /teams/{team}/projects 핸들러처럼 능력의 거부는 403과 메시지로 응답합니다.
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)
}
// ...
}
auth.AuthorizeFor(&team, policies.CreateProject())도 같은 거부 오류를 반환하며 nil 대상은 비로그인으로 처리합니다. bool이 필요하면 auth.Allows(&team, policies.CreateProject())를 사용하세요. 두 함수 모두 팀원별 검사처럼 로그인 사용자 외의 사용자도 검사합니다.
핸들러 밖에서는 위 예의 팀처럼 인수로 받은 사용자를 능력에 직접 전달하세요. 그러면 잡과 명령어에서도 동작합니다.
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
편집할 수 없는 사용자에게 편집 버튼을 숨기려면 페이지도 권한을 알아야 합니다. 서버에서 검사해 뷰나 Inertia 페이지에 전달하세요.
In views
서버 view에서는 버튼 위치의 can에 능력을 전달하세요. cannot은 반대입니다. 뷰는 전달받은 함수만 호출하므로 users and abilities처럼 bootstrap/app.go의 ViewFuncs에 폴리시 함수를 추가한 뒤 템플릿에서 분기하세요.
{{if can (updatePost .Post)}}
<a href="{{route "posts.edit" "post" .Post.ID}}">Edit</a>
{{end}}
With Inertia
Inertia에서는 핸들러에서 확인하고 props로 전달하세요.
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},
})
}
글 생성 여부처럼 모든 페이지에 필요한 능력은 bootstrap/app.go의 Inertia 미들웨어의 share에서 반환하세요. 점이 있는 키는 auth.user 옆의 공유 auth prop에 추가됩니다.
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
}
버튼 숨김은 엔드포인트를 보호하지 않으므로 핸들러에서도 auth.Authorize를 호출해야 합니다.
Testing
인가 테스트에서는 ActingAs로 여러 사용자로 요청하고 각 응답을 검사하세요. 다음은 policy responses의 UpdatePost를 기대합니다.
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)
}
능력은 일반 함수이므로 policies.UpdatePost(&post)(&user)처럼 직접 만든 레코드로 단위 테스트할 수 있습니다. orAdmin 같은 래퍼도 직접 호출 시 실행됩니다.