Laravel策略一直允许用户

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

我已经在下面创建了一个用户策略 App\Policies\UserPolicy 对于 UserController 只允许id2的用户访问。但是现在,即使是id1的用户也可以访问,而且不会出现任何错误。

/**
 * 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();

    }
}

我回来的时候 $this->authorize('create' , $user); 来自 UserController@showCreateProfileForm ,它一直在返回

{
  "allowed": true,
  "message": null,
  "code": null
}
php laravel policy
1个回答
0
投票

刚刚发现在AuthServiceProvider@boot中有这样一个方法。

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

因此,我所有的授权一直失败。

解决的办法是把它改成

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

谢谢你了

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.