Home  >  Article  >  Web Front-end  >  Example of how to complete user authorization using policy in Laravel

Example of how to complete user authorization using policy in Laravel

小云云
小云云Original
2018-03-13 14:47:462344browse

Laravel provides a simpler way to handle user authorization actions. Similar to user authentication, Laravel has 2 main ways to implement user authorization: gates and policies. Record the usage of Policy here. Using Policy to complete user authorization mainly includes three steps:

Define policy class
Register policy class and model association
Policy judgment

Define policy class

A policy is a class that organizes authorization logic in a specific model or resource. For example, if the application is a blog, there will be a Post model and a corresponding PostPolicy to authorize user actions, such as creating or updating a blog or deleting a blog.

You can use the artisan command to create a policy class at this time. The following command creates an empty Post policy class

php artisan make:policy PostPolicy

The generated policy will be placed in the app/Policies directory. If this directory does not exist in your application, Laravel will automatically create it

If you want to generate a strategy class containing CURD, you can use the following artisan command

php artisan make:policy PostPolicy --model=Post

to register the strategy class and model Association

Register the policy class in AuthServiceProvider

    protected $policies = [        //'App\Model' => 'App\Policies\ModelPolicy',  这个是laravel中默认注册了的policy,可以模仿这个注册我们自己的policy        'App\Post' => 'App\Policies\PostPolicy', //注册Post的policy
    ];

The association between the policy class and the model is to write our policy method in policy

<?phpnamespace App\Policies;use App\User;use App\Post;use Illuminate\Auth\Access\HandlesAuthorization;class PostPolicy{
    use HandlesAuthorization;    /**
     * Determine whether the user can update the post.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function update(User $user, Post $post)
    {
        //
        return $user->id === $post->user_id;
    }    /**
     * Determine whether the user can delete the post.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function delete(User $user, Post $post)
    {
        //
        return $user->id === $post->user_id;
    }

The update method accepts User and Post instances as parameter, and should return true or false to indicate whether the user is authorized to update the given Post. Therefore, in this example, we determine whether the user's id matches the user_id in the post.

Strategy Judgment

Here we use the controller auxiliary function in the controller to make policy judgment

//文章编辑逻辑
    public function update(Post $post)
    {
        $this->validate(request(),[            &#39;title&#39;      => &#39;required|String|min:5|max:50&#39;,            &#39;content&#39;    => &#39;required|String|min:10&#39;,
        ]);
        $this->authorize(&#39;update&#39;,$post);         ////////////////////策略判断
        $post->title = request(&#39;title&#39;);
        $post->content = request(&#39;content&#39;);
        $post->save();        return redirect("/posts/{$post->id}");
    }    //文章删除
    public function delete(Post $post)
    {        //TODO::权限验证
        $this->authorize(&#39;delete&#39;,$post);           //////////////////策略判断
        $post->delete();        return redirect(&#39;/posts&#39;);
    }

As long as the verification fails, laravel will automatically throw an HttpException This action is unauthorized.

During development, we may need to determine whether to display some buttons based on the user's permissions, such as editing in the view Or a modified button, in blade we can use @can to specify whether the model button displays

Laravel provides a simpler way to handle users Authorize action. Similar to user authentication, Laravel has 2 main ways to implement user authorization: gates and policies.

Record the usage of Policy here. Using Policy to complete user authorization mainly includes three steps:

Define policy class
Register policy class and model association
Policy judgment

Define policy class

A policy is a class that organizes authorization logic in a specific model or resource. For example, if the application is a blog, there will be a Post model and a corresponding PostPolicy to authorize user actions, such as creating or updating a blog or deleting a blog.

You can use the artisan command to create a policy class at this time. The following command creates an empty Post policy class

php artisan make:policy PostPolicy

The generated policy will be placed in the app/Policies directory. If this directory does not exist in your application, Laravel will automatically create it

If you want to generate a strategy class containing CURD, you can use the following artisan command

php artisan make:policy PostPolicy --model=Post

to register the strategy class and model Association

Register the policy class in AuthServiceProvider

    protected $policies = [        //&#39;App\Model&#39; => &#39;App\Policies\ModelPolicy&#39;,  这个是laravel中默认注册了的policy,可以模仿这个注册我们自己的policy        &#39;App\Post&#39; => &#39;App\Policies\PostPolicy&#39;, //注册Post的policy
    ];

The association between the policy class and the model is to write our policy method in policy

<?phpnamespace App\Policies;use App\User;use App\Post;use Illuminate\Auth\Access\HandlesAuthorization;class PostPolicy{
    use HandlesAuthorization;    /**
     * Determine whether the user can update the post.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function update(User $user, Post $post)
    {
        //
        return $user->id === $post->user_id;
    }    /**
     * Determine whether the user can delete the post.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function delete(User $user, Post $post)
    {
        //
        return $user->id === $post->user_id;
    }

The update method accepts User and Post instances as parameter, and should return true or false to indicate whether the user is authorized to update the given Post. Therefore, in this example, we determine whether the user's id matches the user_id in the post.

Strategy Judgment

Here we use the controller auxiliary function in the controller to make policy judgment

//文章编辑逻辑
    public function update(Post $post)
    {
        $this->validate(request(),[            &#39;title&#39;      => &#39;required|String|min:5|max:50&#39;,            &#39;content&#39;    => &#39;required|String|min:10&#39;,
        ]);
        $this->authorize(&#39;update&#39;,$post);         ////////////////////策略判断
        $post->title = request(&#39;title&#39;);
        $post->content = request(&#39;content&#39;);
        $post->save();        return redirect("/posts/{$post->id}");
    }    //文章删除
    public function delete(Post $post)
    {        //TODO::权限验证
        $this->authorize(&#39;delete&#39;,$post);           //////////////////策略判断
        $post->delete();        return redirect(&#39;/posts&#39;);
    }

As long as the verification fails, laravel will automatically throw an HttpException This action is unauthorized.

During development, we may need to determine whether to display some buttons based on the user's permissions, such as editing in the view Or a modified button. In blade we can use @can to specify whether the model button is displayed.

The above is the detailed content of Example of how to complete user authorization using policy in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn