Authorization
Introduction
authentication이 현재 사용자가 누구인지 확인한다면 인가는 그 사용자가 어떤 작업을 수행할 수 있는지 결정합니다. 예를 들어 블로그에서는 모든 사용자가 게시된 글을 읽을 수 있지만 수정하거나 삭제하는 것은 작성자만 가능할 수 있습니다.
Laravel은 인가 규칙을 폴리시로 구성합니다. 각 폴리시는 특정 모델이나 리소스에 대한 권한(update, delete 등)을 메서드로 정의하는 구조체입니다. 권한 검사에 폴리시 메서드 자체를 전달하므로 이름의 오타나 모델 타입 불일치는 컴파일 시점에 발견됩니다.
user.authorize(PostPolicy::update, &post).await?;
Writing policies
impl 블록에 #[policy]를 지정해 폴리시를 정의합니다. 일반적으로 모델 이름을 딴 유닛 구조체에 정의합니다. 각 메서드는 먼저 사용자를 받고 해당하는 경우 모델을 받은 뒤 작업 허용 여부를 반환합니다.
각 Post 모델이 작성자의 user_id를 저장한다고 가정합니다. 다음 폴리시는 src/policies/post.rs 또는 모델과 같은 src/models/post.rs에 작성하며, 작성자만 글을 수정하거나 삭제하도록 허용합니다.
use laravel::auth::policy;
use crate::models::{Post, User};
pub struct PostPolicy;
#[policy]
impl PostPolicy {
pub fn update(user: &User, post: &Post) -> bool {
user.id == post.user_id
}
pub fn delete(user: &User, post: &Post) -> bool {
user.id == post.user_id
}
}
src/models/post.rs에서 모델과 함께 폴리시를 정의했다면 src/models/mod.rs에서 다시 내보내세요.
// src/models/mod.rs
mod post;
mod user;
pub use post::{Post, PostFactory, PostPolicy};
pub use user::{User, UserFactory};
폴리시를 별도의 src/policies 디렉터리에 두려면 adding your own modules에 설명된 대로 src/lib.rs에 policies 모듈을 선언하고 src/policies/mod.rs에서 각 폴리시를 다시 내보내세요.
// src/lib.rs
pub mod policies;
// src/policies/mod.rs
mod post;
pub use post::PostPolicy;
각 메서드 이름은 허용하는 작업에 맞게 지정합니다. 일반적인 이름은 view_any, view, create, update, delete, restore, force_delete이며, 애플리케이션에 필요한 권한을 자유롭게 추가할 수 있습니다.
#[policy]는 블록 안의 모든 함수를 권한으로 취급하므로 공용 헬퍼 함수는 #[policy]가 없는 별도의 impl 블록에 둡니다.
#[policy]
impl PostPolicy {
pub fn update(user: &User, post: &Post) -> bool {
Self::owns(user, post)
}
pub fn delete(user: &User, post: &Post) -> bool {
Self::owns(user, post)
}
}
impl PostPolicy {
fn owns(user: &User, post: &Post) -> bool {
user.id == post.user_id
}
}
Policy responses
폴리시 메서드가 false를 반환하면 403 상태와 기본 메시지 "This action is unauthorized."로 작업을 거부합니다. 사용자 지정 거부 메시지를 반환하려면 Access::allow()와 Access::deny(..)를 사용해 Access 응답을 반환합니다.
use laravel::auth::{Access, policy};
#[policy]
impl PostPolicy {
pub fn update(user: &User, post: &Post) -> Access {
if user.id == post.user_id {
Access::allow()
} else {
Access::deny("You do not own this post.")
}
}
}
다른 팀의 비공개 프로젝트처럼 권한 없는 사용자에게 레코드 존재 여부를 숨기려면 Access::deny_as_not_found()를 반환합니다. 이 메서드는 403 대신 404 상태로 응답합니다.
#[policy]
impl ProjectPolicy {
pub fn view(user: &User, project: &Project) -> Access {
if user.team_id == project.team_id {
Access::allow()
} else {
Access::deny_as_not_found()
}
}
}
다른 HTTP 상태 코드가 필요하다면 Access::deny_with_status(..)를 호출합니다. 지정한 상태 코드와 표준 사유 문구로 응답합니다.
Access::deny_with_status(401)
Abilities without a record
글 생성처럼 아직 레코드가 없는 권한도 있습니다. 이런 메서드는 사용자만 받습니다. 다음 예는 이메일 인증을 마친 사용자가 글을 만들 수 있도록 허용합니다.
#[policy]
impl PostPolicy {
pub fn create(user: &User) -> bool {
user.email_verified_at.is_some()
}
// ...
}
관리자 대시보드 보기처럼 특정 모델과 관련 없는 권한은 별도 폴리시에 둡니다. 예를 들어 사용자에 is_admin 컬럼이 있다고 가정합니다.
use laravel::auth::policy;
use crate::models::User;
pub struct AdminPolicy;
#[policy]
impl AdminPolicy {
pub fn view_dashboard(user: &User) -> bool {
user.is_admin
}
}
Guests
기본적으로 &User를 받는 폴리시 메서드는 게스트에 대해 실행되지 않고 자동으로 거부합니다. 게스트를 명시적으로 평가하려면 Option<&User>를 받아야 하며, 인증하지 않은 방문자에게는 None이 전달됩니다. 다음은 글에 published 컬럼이 있어 게시된 글은 누구나 보고 초안은 작성자만 볼 수 있는 예입니다.
#[policy]
impl PostPolicy {
pub fn view(user: Option<&User>, post: &Post) -> bool {
post.published || user.is_some_and(|user| user.id == post.user_id)
}
// ...
}
Allowing administrators everything
폴리시가 다루는 모든 작업을 수행할 수 있는 관리자가 있을 수 있습니다. 모든 메서드에서 is_admin을 검사하는 대신 before 메서드를 추가하세요. 사용자를 받아 Option<bool>을 반환합니다.
#[policy]
impl PostPolicy {
fn before(user: &User) -> Option<bool> {
user.is_admin.then_some(true)
}
// ...
}
before 메서드는 폴리시의 다른 모든 메서드보다 먼저 자동으로 실행됩니다.
Some(true)를 반환하면 요청한 권한 메서드를 실행하지 않고 즉시 허용합니다.Some(false)를 반환하면 즉시 거부합니다.None을 반환하면update나delete같은 요청된 권한 메서드로 넘어가 해당 메서드가 판단합니다.
before는 &User를 받으므로 인증되지 않은 게스트에게는 실행되지 않습니다. 따라서 Option<&User>를 받는 게스트 접근 가능 메서드에서 게스트를 직접 평가할 수 있습니다.
관리자에게 글 영구 삭제를 제외한 모든 작업을 허용하는 경우처럼 before에서 검사할 권한을 알아야 한다면, 메서드 이름을 두 번째 &str 파라미터로 받습니다.
#[policy]
impl PostPolicy {
fn before(user: &User, ability: &str) -> Option<bool> {
if ability == "force_delete" {
return None;
}
user.is_admin.then_some(true)
}
// ...
}
Asynchronous checks
인가 검사에 데이터베이스 조회가 필요하면 폴리시 메서드를 async로 만들고 laravel::Result를 반환합니다. 다음 폴리시는 댓글이 없는 글만 작성자가 삭제하도록 허용합니다.
use laravel::auth::{Access, policy};
use crate::models::{Comment, Post, User};
#[policy]
impl PostPolicy {
pub async fn delete(user: &User, post: &Post) -> laravel::Result<Access> {
if user.id != post.user_id {
return Ok(Access::deny("You do not own this post."));
}
if Comment::query().filter(Comment::post_id.eq(post.id)).exists().await? {
return Ok(Access::deny("You can't delete a post with comments."));
}
Ok(Access::allow())
}
// ...
}
비동기 폴리시 메서드가 데이터베이스 쿼리 실패 등으로 Err를 반환하면 Laravel은 인가 거부로 처리하지 않고 500 서버 오류로 요청을 실패 처리합니다.
Checking abilities
폴리시를 정의한 뒤에는 핸들러에서 사용자 타입의 authorize나 can에 폴리시 메서드와 필요한 추가 인수를 순서대로 전달해 권한을 검사합니다.
핸들러에서는 Authenticated<User>로 로그인한 사용자를 추출하고 route model binding으로 대상 모델을 확인합니다.
use laravel::inertia::{self, Page, props};
use laravel::prelude::*;
use crate::models::{Post, User};
use crate::policies::post::PostPolicy;
pub async fn edit(
user: Authenticated<User>,
post: Post,
) -> laravel::Result<Page> {
user.authorize(PostPolicy::update, &post).await?;
Ok(inertia::render("Posts/Edit", props! { "post" => &post }))
}
pub async fn show(
user: Authenticated<User>,
post: Post,
) -> laravel::Result<Page> {
let can_delete = user.can(PostPolicy::delete, &post).await?;
Ok(inertia::render("Posts/Show", props! { "post" => &post, "canDelete" => can_delete }))
}
authorize는 거부되면 오류를 반환하므로 ?가 configured status and message로 핸들러를 중단합니다. can은 bool을 반환하므로 직접 분기할 수 있습니다.
두 메서드는 prelude가 가져오는 Authorizable 트레이트에서 제공되며, 모든 Authenticatable 모델에 자동으로 구현됩니다.
PostPolicy::create처럼 사용자 외에 모델이나 추가 인수를 받지 않는 권한은 두 번째 인수로 ()를 전달합니다.
pub async fn create(user: Authenticated<User>) -> laravel::Result<Page> {
user.authorize(PostPolicy::create, ()).await?;
Ok(inertia::render("Posts/Create", props! {}))
}
Authorizing via Auth or Request
로그인한 사용자뿐 아니라 게스트도 접근할 수 있는 라우트에서는 Auth<User>나 Request의 can 또는 authorize를 호출합니다.
use laravel::auth::Auth;
use laravel::inertia::Page;
use laravel::prelude::*;
use crate::models::{Post, User};
use crate::policies::post::PostPolicy;
pub async fn show(auth: Auth<User>, post: Post) -> laravel::Result<Page> {
auth.authorize(PostPolicy::view, &post).await?;
// ...
}
pub async fn create(request: Request) -> laravel::Result<Page> {
request.authorize(PostPolicy::create, ()).await?;
// ...
}
폴리시 메서드가 Option<&User>를 받지 않으면 게스트는 authorize에서 403을, can에서 false를 받습니다.
Passing more arguments
판단이 여러 모델에 의존하면 폴리시 메서드는 사용자 뒤에 최대 3개의 추가 인수를 받을 수 있습니다. 예를 들어 작성자가 글을 Category로 옮기되 카테고리가 잠겨 있지 않아야 한다고 가정합니다.
use laravel::auth::policy;
use crate::models::{Category, Post, User};
#[policy]
impl PostPolicy {
pub fn move_to(user: &User, post: &Post, category: &Category) -> bool {
user.id == post.user_id && !category.locked
}
// ...
}
2개 또는 3개의 인수는 메서드 순서대로 튜플에 넣어 전달합니다.
user.authorize(PostPolicy::move_to, (&post, &category)).await?;
Authorizing a form
form type은 #[validate(authorize(..))]로 수신 요청을 자동 인가할 수 있어 핸들러에서 직접 authorize를 호출할 필요가 없습니다. 폴리시 메서드가 /posts/{post} 라우트의 Post처럼 모델을 요구하면 route("post")를 전달하여 라우트 파라미터를 해석하고 폴리시에 모델을 전달합니다.
use laravel::prelude::*;
use crate::models::Post;
use crate::policies::post::PostPolicy;
#[laravel::input]
#[validate(authorize(PostPolicy::update, route("post")))]
pub struct UpdatePost {
#[validate(required, max_length(255))]
title: String,
}
pub async fn update(post: Post, Valid(input): Valid<UpdatePost>) -> laravel::Result<Redirect> {
// Only users who may update the post get here, with a valid title...
Ok(Redirect::back())
}
Valid<UpdatePost>는 입력 검증 전에 현재 사용자에 대해 PostPolicy::update를 검사합니다. 글을 수정할 수 없는 사용자는 유효성 검증 오류가 아닌 거부 응답을 받습니다.
레코드가 없는 권한은 #[validate(authorize(PostPolicy::create))]처럼 인수를 생략합니다. 여러 레코드는 authorize(PostPolicy::move_to, route("post"), route("category"))처럼 메서드 순서대로 나열합니다.
Checking types other than users
프로젝트 수를 요금제로 제한하는 팀처럼 사용자 이외의 타입에도 폴리시로 권한을 결정할 수 있습니다. 빈 impl로 해당 타입에 Authorizable을 구현하고 폴리시의 첫 인수에 그 타입을 사용합니다.
use laravel::auth::{Authorizable, policy};
use crate::models::Team;
impl Authorizable for Team {}
pub struct ProjectPolicy;
#[policy]
impl ProjectPolicy {
pub fn create(team: &Team) -> bool {
team.projects_count < team.project_limit
}
}
이제 /teams/{team}/projects 라우트의 핸들러 등에서 사용자를 검사하듯 팀을 검사합니다.
pub async fn store(team: Team) -> laravel::Result<Redirect> {
team.authorize(ProjectPolicy::create, ()).await?;
// ...
}
한 폴리시의 모든 메서드는 첫 인수로 같은 타입을 받습니다. 사용자와 팀의 권한을 모두 검사하려면 각각 폴리시를 작성하세요.
Sharing abilities with the frontend
페이지에서 수정 권한이 없는 사용자에게 Edit 버튼을 숨기는 등 사용자가 무엇을 할 수 있는지 알아야 하는 경우가 많습니다. 서버에서 권한을 검사하고 결과를 뷰나 Inertia 페이지에 전달하세요.
In views
서버 렌더링 views에서는 핸들러에서 권한을 평가하고 data!로 전달합니다.
use laravel::prelude::*;
use laravel::view::View;
use crate::models::{Post, User};
use crate::policies::post::PostPolicy;
pub async fn show(user: Authenticated<User>, post: Post) -> laravel::Result<View> {
let can = data! {
update => user.can(PostPolicy::update, &post).await?,
delete => user.can(PostPolicy::delete, &post).await?,
};
Ok(view("posts.show", data! { post, can }))
}
그다음 템플릿에서 해당 불리언 값으로 분기합니다.
{% if can.update %}
<a href="/posts/{{ post.id }}/edit">Edit</a>
{% endif %}
모든 템플릿에서 필요한 권한은 미들웨어 안의 laravel::view::share로 현재 요청에 공유합니다.
With Inertia
Inertia에서는 검사한 권한을 props로 전달합니다.
use laravel::inertia::{self, Page, props};
use laravel::prelude::*;
use serde_json::json;
use crate::models::{Post, User};
use crate::policies::post::PostPolicy;
pub async fn show(
user: Authenticated<User>,
post: Post,
) -> laravel::Result<Page> {
let can = json!({
"update": user.can(PostPolicy::update, &post).await?,
"delete": user.can(PostPolicy::delete, &post).await?,
});
Ok(inertia::render("Posts/Show", props! { "post" => &post, "can" => can }))
}
사용자의 글 생성 가능 여부처럼 모든 페이지가 필요한 권한은 src/http/middleware에 있는 Inertia 미들웨어의 share 메서드에서 반환합니다.
use laravel::http::Request;
use laravel::inertia::{self, Props, props};
use serde_json::json;
use crate::models::User;
use crate::policies::post::PostPolicy;
impl inertia::Middleware for HandleInertiaRequests {
async fn share(&self, request: &Request) -> laravel::Result<Props> {
let user: Option<User> = request.user().await?;
Ok(props! {
auth => json!({
"user": user,
"permissions": {
"post": { "create": request.can(PostPolicy::create, ()).await? },
},
}),
})
}
}
버튼을 숨겨도 엔드포인트가 보호되는 것은 아니므로 해당 작업의 핸들러에서 여전히 authorize를 호출해야 합니다.
Testing
핸들러의 인가를 테스트하려면 acting_as로 서로 다른 사용자로 요청을 보내고 각 응답을 검사합니다.
use laravel::model::create;
use laravel::testing::prelude::*;
#[laravel::test]
async fn only_the_author_may_update_a_post(app: Application) -> laravel::Result<()> {
let author = create!(User {
name: "Taylor",
password: "password",
})
.await?;
let other = create!(User {
name: "Abigail",
password: "password",
})
.await?;
let post = create!(Post { user_id: author.id, title: "Hello", published: true }).await?;
app.put(format!("/posts/{}", post.id))
.acting_as(&other)
.json(json!({ "title": "Goodbye" }))
.await
.assert_forbidden()
.assert_json_path("message", "You do not own this post.");
app.put(format!("/posts/{}", post.id))
.acting_as(&author)
.json(json!({ "title": "Goodbye" }))
.await
.assert_redirect();
Ok(())
}
폴리시 메서드는 일반 함수이므로 단위 테스트에서 생성한 레코드로 PostPolicy::update(&user, &post)처럼 직접 호출할 수도 있습니다. 직접 호출해도 before가 실행됩니다.