跳至正文

授权 ​

简介 ​

身份认证用于识别当前用户,授权则决定该用户可以执行哪些操作。例如,在博客应用中,任何用户都能阅读已发布的文章,只有作者可以编辑或删除文章。

Laravel 使用策略组织授权规则。每个策略都是一个结构体,其方法为特定模型或资源定义操作权限(例如 update 或 delete)。检查权限时直接传入策略方法,编译器就能发现拼错的方法名或不匹配的模型类型:

rust
user.authorize(PostPolicy::update, &post).await?;

编写策略 ​

给 impl 块添加 #[policy] 属性即可定义策略,通常使用以模型命名的单元结构体。每个方法的第一个参数是用户,之后是模型(如果需要),返回值表示操作是否被允许。

假设每个 Post 模型都保存了作者的 user_id。下面的策略可以放在 src/policies/post.rs 中,也可以与模型一起放在 src/models/post.rs,只允许作者更新或删除文章:

rust
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 重新导出策略:

rust
// src/models/mod.rs
mod post;
mod user;

pub use post::{Post, PostFactory, PostPolicy};
pub use user::{User, UserFactory};

如果希望将策略集中在独立的 src/policies 目录下,请在 src/lib.rs 中声明 policies 模块(见添加自己的模块),并从 src/policies/mod.rs 重新导出各个策略:

rust
// 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 块中:

rust
#[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
    }
}

策略响应 ​

返回 false 的策略方法会拒绝操作,使用 403 状态和默认消息 “This action is unauthorized.”。要自定义拒绝消息,可使用 Access::allow() 和 Access::deny(..) 返回 Access 响应:

rust
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(),使用 404 状态代替 403:

rust
#[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(..),它会以指定状态码及其标准原因短语响应:

rust
Access::deny_with_status(401)

无需记录的权限 ​

某些操作尚不涉及具体记录,例如创建文章。相应的策略方法只接收用户。下面的策略允许用户在验证邮箱后创建文章:

rust
#[policy]
impl PostPolicy {
    pub fn create(user: &User) -> bool {
        user.email_verified_at.is_some()
    }

    // ...
}

对于查看管理面板等不涉及任何特定模型的操作,可以单独定义策略。例如,假设用户具有 is_admin 列:

rust
use laravel::auth::policy;

use crate::models::User;

pub struct AdminPolicy;

#[policy]
impl AdminPolicy {
    pub fn view_dashboard(user: &User) -> bool {
        user.is_admin
    }
}

访客 ​

默认情况下,接收 &User 的策略方法会直接拒绝访客,并跳过方法体。要显式判断访客权限,请接收 Option<&User>,未认证的访客对应 None。例如,假设文章有 published 列,任何人都可以查看已发布的文章,只有作者可以查看草稿:

rust
#[policy]
impl PostPolicy {
    pub fn view(user: Option<&User>, post: &Post) -> bool {
        post.published || user.is_some_and(|user| user.id == post.user_id)
    }

    // ...
}

授予管理员全部权限 ​

如果管理员可以执行某个策略涵盖的所有操作,可以添加 before 方法,统一处理各方法中的 is_admin 检查。它接收用户并返回 Option<bool>:

rust
#[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 参数接收方法名:

rust
#[policy]
impl PostPolicy {
    fn before(user: &User, ability: &str) -> Option<bool> {
        if ability == "force_delete" {
            return None;
        }

        user.is_admin.then_some(true)
    }

    // ...
}

异步检查 ​

授权检查需要查询数据库时,请将策略方法声明为 async 并返回 laravel::Result。例如,下面的策略只允许作者删除尚无评论的文章:

rust
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 服务器错误,使该请求失败。拒绝授权与服务器故障有各自的响应方式。

检查权限 ​

策略定义完成后,可以在处理器中调用用户类型的 authorize 或 can 方法,传入策略方法,随后按需传入其他参数。

在处理器中,通过 Authenticated<User> 提取已登录用户,并通过路由模型绑定解析目标模型:

rust
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 在拒绝授权时返回错误,使用 ? 会终止处理器并返回配置的状态与消息;can 则返回 bool,供你自行决定后续分支。

这两个方法来自 prelude 中导入的 Authorizable trait,每个 Authenticatable 模型都自动实现了它。

如果权限方法只接收用户,没有模型或额外参数(例如 PostPolicy::create),请将 () 作为第二个参数:

rust
pub async fn create(user: Authenticated<User>) -> laravel::Result<Page> {
    user.authorize(PostPolicy::create, ()).await?;

    Ok(inertia::render("Posts/Create", props! {}))
}

通过 Auth 或 Request 授权 ​

对于访客和登录用户都能访问的路由,可以在 Auth<User> 或 Request 上调用 can 或 authorize:

rust
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。

传入更多参数 ​

当授权决定涉及多个模型时,在用户之外,策略方法最多可接收三个额外参数。例如,假设只有当 Category 未锁定时,作者才可以将文章移入该分类:

rust
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
    }

    // ...
}

将两个或三个参数按方法定义的顺序组成元组传入:

rust
user.authorize(PostPolicy::move_to, (&post, &category)).await?;

表单授权 ​

表单类型可以用 #[validate(authorize(..))] 自动验证传入请求是否获得授权,处理器因此无需自行调用 authorize。如果策略方法需要模型(例如 /posts/{post} 路由上的 Post),请传入 route("post") 以解析相应的路由参数并将模型传给策略:

rust
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> {
    // 只有获准更新文章且提交了有效标题的用户才会执行到这里……

    Ok(Redirect::back())
}

Valid<UpdatePost> 会先为当前用户检查 PostPolicy::update,再验证输入。没有权限更新文章的用户会直接收到拒绝授权的响应。

对于无需记录的权限,可以像 #[validate(authorize(PostPolicy::create))] 一样省略参数。涉及多条记录时,按方法定义的顺序列出,例如 authorize(PostPolicy::move_to, route("post"), route("category"))。

检查用户之外的类型 ​

策略也可以判断其他类型的权限,例如某个团队按套餐最多可以创建多少个项目。用空的 impl 为该类型实现 Authorizable,再编写以该类型为首个参数的策略:

rust
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 路由的处理器中:

rust
pub async fn store(team: Team) -> laravel::Result<Redirect> {
    team.authorize(ProjectPolicy::create, ()).await?;

    // ...
}

同一策略的所有方法都使用相同类型作为首个参数。若需同时检查用户和团队的权限,请分别定义策略。

与前端共享权限 ​

页面经常需要知道用户允许执行的操作,例如对没有编辑权限的用户隐藏编辑按钮。请在服务器上检查权限,然后将结果传给视图或 Inertia 页面。

在视图中使用 ​

对于服务端渲染的视图,请在处理器中评估权限并通过 data! 传递结果:

rust
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 }))
}

在模板中根据得到的布尔值选择分支:

html
{% if can.update %}
    <a href="/posts/{{ post.id }}/edit">Edit</a>
{% endif %}

对于每个模板都需要的权限,可以在中间件中使用 laravel::view::share,在当前请求内共享结果。

在 Inertia 中使用 ​

使用 Inertia 时,可将检查后的权限结果作为 props 传入:

rust
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 方法返回:

rust
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。

测试 ​

要测试处理器的授权行为,请通过 acting_as 以不同的用户身份发送请求,再检查各自的响应:

rust
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",
        email: "taylor@laravel.com",
        password: "password",
    })
    .await?;

    let other = create!(User {
        name: "Abigail",
        email: "abigail@laravel.com",
        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。