使用policy's ->authorize()在store()方法中的laravel控制器中签入


Using a policy's this->authorize() check in a laravel controller inside a store() method

所以我正在阅读关于使用laravel策略授予我的应用程序资源的权限,但是似乎有一个问题,尽管我遵循了教程。

我有一个用户模型,它不能通过HTTP请求创建,除非其他用户具有委托角色的'Admin'或'Broker'。我理解并成功地将它用于其他操作,如索引用户,如下所示:

在私有$policies数组内的AuthServiceProvider.php中,我将用户类注册为UserPolicy类,如下所示

class AuthServiceProvider extends ServiceProvider {
    protected $policies = [
        'App'Model' => 'App'Policies'ModelPolicy',
        User::class => UserPolicy::class,
        Insured::class => InsuredPolicy::class
    ];
    public function boot(GateContract $gate)
    {
        $this->registerPolicies($gate);
    }
}

定义UserPolicy控制器类

class UserPolicy {
    use HandlesAuthorization;
    protected $user;
    public function __construct(User $user) {
        $this->user = $user;
    }
    public function index(User $user) {
        $is_authorized = $user->hasRole('Admin');
        return $is_authorized;
    }
    public function show(User $user, User $user_res) {
        $is_authorized = ($user->id == $user_res->id);
        return $is_authorized;    
    }
    public function store() {
        $is_authorized = $user->hasRole('Admin');
        return $is_authorized;
    }
}

然后在UserController类中,在执行关键操作之前,根据用户

的权限,我使用this->authorize() check来停止或继续
class UserController extends Controller
{
    public function index()
    {
        //temporary authentication here
        $users = User::all();
        $this->authorize('index', User::class);
        return $users;
    }
    public function show($id)
    {
        $user = User::find($id);
        $this->authorize('show', $user);
        return $user;
    }
    public function store(Request $request) {

        $user = new User;
        $user->name = $request->get('name');
        $user->email = $request->get('email');
        $user->password = 'Hash::make($request->get('password'));
        $this->authorize('store', User::class);
        $user->save();
        return $user;
    }
}

问题是 $this->authorize()总是在store操作返回异常时停止进程:此操作是未经授权的。

我为authorize()的参数尝试了多种变体,但无法让它像索引操作

那样工作

UserPolicy::classstore()函数中,您没有传递用户模型对象:

public function store(User $user) {
   $is_authorized = $user->hasRole('Admin');
   return true;
}

缺少参数User $user .

也许这就是问题的原因。