我只是想向任何想要看到authServiceProvider的人展示一家公司:
Company::class => CompanyPolicy::class ,
'App\Models\Company' => 'App\Policies\CompanyPolicy',
公司的政策
public function view( Company $company)
{
return true ;
}
companyController
public function __construct(CompanyRepository $companies)
{
$this->companies = $companies;
}
public function show(Company $company)
{
$this->authorize('view', $company);
return $this->companyRepository->show($company);
}
路由到控制器:
Route::apiResource('companies', 'CompanyController');
它始终返回此操作未经授权。为什么?
Company::class => CompanyPolicy::class,
的线在你的AuthServiceProvier
是多余的,你必须删除它。
让我举一个例子:
假设我们有一个名为SomeModel
的模型并已注册其政策。该策略有view
的方法,检查当前用户是否能够调用show方法。
对于api
的守卫你可以创建一个如下所示的trait
:
trait ApiTrait
{
/**
* Authorize a given action for the current user.
*
* @param mixed $ability
* @param mixed|array $arguments
* @return \Illuminate\Auth\Access\Response
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function authorizeApi($ability, $arguments)
{
if (!request()->user('api')->can($ability, $arguments)) {
abort(403, 'This action is unauthorized.');
}
}
}
然后在你的控制器中使用它:
class ExampleController extends Controller
{
use ApiTrait;
public function show(SomeModel $something)
{
$this->authorize('view', $something);
return 'it workes';
}
}
注意你应该使用auth:api
的中间件来保护你的路线,否则你会在can
中调用ApiTrait
方法时得到错误代码500。