我在线查看了文档https://laravel.com/docs/5.2/authorization#controller-authorization和一些教程,我确信我已经做好了一切。但是,我无法获得政策在laravel 5.2中工作 我创建了一个策略类
use App\User;
use App\Gallery;
use Illuminate\Auth\Access\HandlesAuthorization;
class GalleryPolicy
{
use HandlesAuthorization;
/**
* Create a new policy instance.
*
* @return void
*/
public function __construct()
{
//
}
public function saveTitle(User $user, Gallery $gallery)
{
return true;
// return $user->id === $gallery->user_id;
}
}
我在AuthServiceProvider中注册了这个
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
'App\Gallery' => 'App\Policies\GalleryPolicy',
];
现在在我的控制器中我称之为
$gallery = Gallery::where('hash', $request->gallery)->first();
$this->authorize('saveTitle', $gallery);
我得到了这个输出: 哎呀,看起来像出事了。 Handler.php第107行中的1/1 HttpException:此操作未经授权。
答案 0 :(得分:0)
据我所知,您的政策有效,但您没有抓住授权方法抛出的异常。
如果授权失败,AuthorizesRequests trait会抛出HttpException。如果你没有捕获它,异常处理程序会捕获异常,并在你的问题中写入时显示给你。
<?php
class GalleryController extends Controller {
/**
* Example action.
*/
public function show() {
try {
$gallery = Gallery::where('hash', $request->gallery)->first();
$this->authorize('saveTitle', $gallery);
} catch (\Symfony\Component\HttpKernel\Exception\HttpException $e) {
// Handle the unauthorized request's response here.
}
}
}
有关详细信息,请参阅特征来源:(来自5.1,但大多数情况相同。):
特别是: $ message =&#39;此操作未经授权。&#39;
/**
* Throw an unauthorized exception based on gate results.
*
* @param string $ability
* @param mixed|array $arguments
* @param string $message
* @param \Exception $previousException
* @return \Symfony\Component\HttpKernel\Exception\HttpException
*/
protected function createGateUnauthorizedException($ability, $arguments, $message = 'This action is unauthorized.', $previousException = null)
{
return new HttpException(403, $message, $previousException);
}