【问题标题】:Laravel Policies keeps allowing usersLaravel 政策不断允许用户
【发布时间】:2020-09-27 01:41:56
【问题描述】:

我在App\Policies\UserPolicy 下为UserController 创建了一个用户策略,只允许ID 为2 的用户访问。但是现在即使是 id 为 1 的用户也可以访问而不会抛出任何错误。

/**
 * Determine whether the user can create models.
 *
 * @param  \App\Models\Auth\User  $user
 * @return mixed
 */
public function create(User $user)
{
    return $user->id === 2 ? Response::allow()
    : Response::deny('You do not own this users.');;
}

路线

Route::get('user/createProfile' , [UserController::class, 'showCreateProfileForm'])->name('user.profile.createProfile');

控制器UserController.php

public function showCreateProfileForm()
{
    $user = Auth::user();
    $this->authorize('create' , $user);
    return view('backend.auth.user.profile.create');
}

提供者AuthServiceProvider.php

<?php

namespace App\Providers;

use Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use App\Models\Auth\User;
use App\Policies\UserPolicy;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */ 
    protected $policies = [
        User::class => UserPolicy::class,
    ];

    /**
     * Register any authentication / authorization services.
     */
    public function boot()
    {
        $this->registerPolicies();

    }
}

当我从 UserController@showCreateProfileForm 返回 $this-&gt;authorize('create' , $user); 时,它会不断返回

{
  "allowed": true,
  "message": null,
  "code": null
}

【问题讨论】:

  • 请尝试:$this->authorize('create');并确保你有: $this->authorizeResource(User::class, 'user');在你的控制器构造函数中
  • 不,它不起作用,甚至没有注册该政策。

标签: php laravel policy


【解决方案1】:

刚刚发现AuthServiceProvider@boot里面有这个方法

Gate::before(function ($user, $ability) {
    if ($user->isSuperAdmin()) {
        return true;
    }
});

因此,我的所有授权都失败了。

解决方案是将其更改为

Gate::after(function ($user, $ability) {
    if ($user->isSuperAdmin()) {
        return true;
    }
});

谢谢

【讨论】:

    猜你喜欢
    • 2021-11-07
    • 2012-10-31
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2019-10-11
    • 2020-12-07
    • 1970-01-01
    • 2018-01-03
    相关资源
    最近更新 更多