流明:$ user在Policy

时间:2017-03-11 20:01:15

标签: php laravel authorization lumen

我正在尝试验证用户是否存在于Lumen中的策略中。 这是我的控制器功能:

public function create(Request $request)
{
    $rules = array(
        'content'   => 'required|string',
    );
    $user = $request->user();
    $this->validate($request, $rules);
    $this->authorize('create', Card::class);

这是政策:

public function create(User $user)
{
    // As long as the user is real, allowed
    return $user->id != null;
}

create policy中的$ user似乎为null。这是错误:

HttpException in Handler.php line 90:
This action is unauthorized.
in Handler.php line 90
at Handler->render(object(Request), object(AuthorizationException)) in Handler.php line 48
at Handler->render(object(Request), object(AuthorizationException)) in Pipeline.php line 78
at Pipeline->handleException(object(Request), object(AuthorizationException)) in Pipeline.php line 54
at Pipeline->Laravel\Lumen\Routing\{closure}(object(Request)) in Authenticate.php line 42
at Authenticate->handle(object(Request), object(Closure), 'api') in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Laravel\Lumen\Routing\{closure}(object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in RoutesRequests.php line 780
at Application->sendThroughPipeline(array('App\\Http\\Middleware\\Authenticate:api'), object(Closure)) in RoutesRequests.php line 626
at Application->handleFoundRoute(array(true, array('uses' => 'App\\Http\\Controllers\\CardController@create', 'middleware' => array('auth:api')), array())) in RoutesRequests.php line 528
at Application->Laravel\Lumen\Concerns\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Laravel\Lumen\Routing\{closure}(object(Request)) in ExampleMiddleware.php line 18
at ExampleMiddleware->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Laravel\Lumen\Routing\{closure}(object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in RoutesRequests.php line 780
at Application->sendThroughPipeline(array('App\\Http\\Middleware\\ExampleMiddleware'), object(Closure)) in RoutesRequests.php line 534
at Application->dispatch(object(Request)) in RoutesRequests.php line 475
at Application->run(object(Request)) in index.php line 29

1 个答案:

答案 0 :(得分:2)

我遇到了同样的问题。

但问题与政策类无关。

这可以通过在AuthServiceProvider文件中使用完全限定的类名来解决,

变化:

Gate::policy(Post::class, PostPolicy::class);

为:

Gate::policy(\App\Post::class, \App\Policies\PostPolicy::class);

希望这有帮助。