Laravel中策略授权与功能之间的区别是什么?

问题描述 投票:0回答:2

我正在使用laravel基本策略系统来保护未经授权的用户免受更新。例如,用户有Id 1和In帖子表User_id也是1。

现在以$this->authorize('update',$post);的方式,我只能通过一个变量$post进行身份验证。而在can方法我也可以使用$user变量$user->can('update',$post)进行授权。

这是代码:

在PostPolicy.php中:

public function update(User $user, Post $post)
{
    return $user->id === $post->user_id;
}

在AuthServiceProvider.php中:

protected $policies = [
    Post::class => PostPolicy::class
]

在Controller授权方式:

public function update(Request $request, $id)
{
    $post=Post::find(1);
    $user=User::find(1); 
    $this->authorize('update',$post);
    return 'Hello Everything Access For You ';
}

在Controller中使用can方法:

public function update(Request $request, $id)
{
    $post=Post::find(1);
    $user=User::find(1); 
    if($user->can('update',$post)){
        return 'Your are allowed';
    }
    else
    {
        return 'Your are Not allowed'; 
    }
}

我是否适合这两个功能。有什么区别吗?我必须使用哪种方法。提前致谢。

php laravel laravel-5 laravel-4 laravel-5.2
2个回答
2
投票

如果您使用authorize()can()中的任何一个,则目的是验证用户是否有权执行某些任务。

但是:

  • 对于authorize(),如果失败(从策略方法返回false),则authorize方法将抛出Illuminate \ Auth \ Access \ AuthorizationException,默认的Laravel异常处理程序将转换为带有403的HTTP响应
  • can()的情况下,它只是检查用户是否被授权的基本方法,然后您需要自己处理其余的。如果未经授权,该怎么做。

考虑到上述因素,我认为$this->authorize('update',$post);更容易在控制器中使用。

documentation查看更多相同内容

你也可以这样做:

$request->user()->can()如果你想检查当前请求用户的授权。

更新:

authorize()旨在授权当前登录的用户,其中laravel自动将当前用户传递给策略。

而您可以在任何用户实例上使用can

  • $request->user()->can()如果你想检查当前请求用户的授权。
  • $user = $user::find($id); $user->can(...),如果是其他任何用户

1
投票

$this->authorize()检查当前用户是否被授权。 $user->can()检查$user中的用户是否获得授权。两者都依赖相同的基本政策来做出决定。

两者之间的主要区别在于,如果当前用户未被授权(因为它打算在控制器中使用),$this->authorize()会抛出异常,而$user->can()只返回true / false

如果你想要一个控制器就像为当前不同的用户做$this->authorize()一样,你可以这样做:

// where "123" is the user you want to check against
$user = App\User::find(123);

if(!$user->can('update', $post) {
    throw new \Illuminate\Auth\Access\AuthorizationException;
}

也就是说,这很少是你想做的事情 - 它(通常)没有多大意义来确定当前用户是否可以根据其他用户的权限做某事。

© www.soinside.com 2019 - 2024. All rights reserved.