【问题标题】:Laravel UserPolicy always rejects authorizationLaravel UserPolicy 总是拒绝授权
【发布时间】:2018-04-18 19:04:11
【问题描述】:

我在 Laravel 中创建了一个 UserPolicy,并尝试在控制器中使用 $this->authorize(User::class),但是,当我访问 UserController@index 时,它总是返回 403 错误,如果我删除此问题不存在$this->authorize(User::class) 来自UserController

app/Providers/AuthServiceProvider.php

namespace App\Providers;

use App\Transaction;
use App\Policies\UserPolicy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

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

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

        //
    }
}

app/Policies/UserPolicy.php

namespace App\Policies;

use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class UserPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can index users.
     *
     * @param  \App\User  $model
     * @return mixed
     */
    public function index(User $user)
    {
        return true;
    }
}

app/Controllers/UserController.php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $this->authorize(User::class);
        $users = User::all();
        return view('users.index', compact('users'));
    }
}

【问题讨论】:

  • 尝试传递用户实例而不是类名$this->authorize(auth()->user()) ?
  • @linktoahref 刚刚尝试这样做,但没有任何改变
  • 用户在访问用户控制器的索引路由时是否已经登录?
  • 试试 $this->authorize('index', User::class);
  • 在app/Providers/AuthServiceProvider.php中添加使用App\User;

标签: laravel laravel-5 laravel-5.6


【解决方案1】:

app/Providers/AuthServiceProvider.php 中缺少use App\User;,感谢Mike Foxtech 提供answer in the comments

在 app/Providers/AuthServiceProvider.php 添加使用 App\User;

【讨论】:

  • 救命!这让我很困惑。
猜你喜欢
  • 2019-07-29
  • 2012-12-03
  • 1970-01-01
  • 2011-04-21
  • 1970-01-01
  • 2019-09-26
  • 2015-05-22
  • 1970-01-01
  • 2018-01-07
相关资源
最近更新 更多