该策略不适用于index
apiResource调用。始终返回403
。
我的ProjectPolicy是这样的:
class ProjectPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view any projects.
*
* @param \App\User $user
* @return mixed
*/
public function viewAny(User $user)
{
return true;
}
...
我的ProjectController使用了它:
class ProjectController extends Controller
{
public function __construct()
{
$this->authorizeResource(ProjectPolicy::class, 'project');
}
...
我注册了政策:
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
Project::class => ProjectPolicy::class,
];
除index
方法调用之外的所有方法都可以使用:
/**
* Display a listing of the resource.
*
* @param Request $request
* @return Response
*/
public function index(Request $request)
{
return $request->user()->projects()->get();
}
答案 0 :(得分:1)
在项目控制器构造函数中,您需要授权资源(模型)而不是策略本身
public function __construct()
{
$this->authorizeResource(\App\Project::class, 'project');
}
还请确保发出请求的用户经过身份验证,不能授权来宾
但是如果您想要guests to be authorized,则可以在Policy类的依赖项注入上将User
模型标记为可空/可选
/**
* Determine whether the user can view any projects.
*
* @param \App\User $user
* @return mixed
*/
public function viewAny(?User $user)
{
return true;
}
希望这会有所帮助