我正在尝试用Laravel5.2开发一个RESTful API。我无意中发现了如何以JSON格式返回失败的授权。目前,它正在抛出403页错误,而不是JSON。
控制器:TenantController.php
class TenantController extends Controller
{
public function show($id)
{
$tenant = Tenant::find($id);
if($tenant == null) return response()->json(['error' => "Invalid tenant ID."],400);
$this->authorize('show',$tenant);
return $tenant;
}
}政策:TenantPolicy.php
class TenantPolicy
{
use HandlesAuthorization;
public function show(User $user, Tenant $tenant)
{
$users = $tenant->users();
return $tenant->users->contains($user->id);
}
}该授权目前运行良好,但它显示的是一个403禁止页面,而不是返回json错误。是否可以将它作为403的JSON返回?而且,对于所有失败的授权(不仅仅是在这个控制器中),是否有可能使其成为全局的?
发布于 2016-08-02 02:22:13
我们通过修改在App\Exceptions\Handler.php中找到的异常处理程序来解决这个问题,将它添加到render函数中。
public function render($request, Exception $e)
{
if ($e instanceof AuthorizationException)
{
return response()->json(['error' => 'Not authorized.'],403);
}
return parent::render($request, $e);
}发布于 2016-07-26 06:25:12
是的,在您的策略中创建一个简单的all方法,该方法将在所有其他授权检查之前执行,
public function before($user, $ability,Request $request)
{
if (!yourconditiontrue) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return abort('403');
}
}
}发布于 2017-06-19 00:42:26
您可以拦截异常。
try {
$this->authorize('update', $data);
} catch (\Exception $e)
{
return response()->json(null, 403);
}https://stackoverflow.com/questions/38580890
复制相似问题