如何更改Laravel策略响应状态代码?
我正在使用Laravel 9,
我想防止用户查看另一个用户个人信息。 这是我的策略方法
public function viewUser(User $user, User $model)
{
return $user->id === $model->id;
}
,这是
public function show(User $user)
{
$this->authorize('viewUser', $user);
return view('users.show', compact('user'));
}
它显示的403的
控制器方法,但我想将状态代码更改为404,
public function viewUser(User $user, User $model)
{
return $user->id === $model->id
? Response::allow()
: Response::deny(code: 404);
}
但仍然显示403而不是404。我在策略上做错了什么?我知道我可以使用另一种方法来改变响应,但我对Laravel政策本身的问题。
路线
Route::group([
'middleware' => ['auth'],
'prefix' => 'users/{user}',
'as' => 'users.',
], function () {
Route::get('/', [UserController::class, 'show'])->name('show');
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于Laravel 9.20可以通过
denyasnotfound
方法来实现 - 链接到 docs或使用
denywithstatus()
的更多通用方式Since Laravel 9.20 it can be achieved with
denyAsNotFound
method - link to docsor more universal way with
denyWithStatus()
在
app \ exceptions \ handler.php
中,在render()
方法中,您可以定义当抛出x
异常时应执行的操作。话虽这么说,添加下面的代码应该为您服务:它的作用基本上是检查抛出的异常是否是授权exception(laravel throw in laravel throw中的政策),如果是这样的,请抛出新的NotFoundHttPexception(
404
)。但是,这将把任何和所有授权感知都更改为404,这可能不是想要的行为。更新:
挖掘后,我找到了返回404 的封闭建议。
我个人认为,策略除了403状态代码,因为那是正确的代码,因此禁止使用任何东西。返回404是不正确的,因为该策略找不到找不到X资源。
如果您真的想要,则可以更改
handler.php
。我觉得这不是使用策略的正确方法,但这是重点。上面提到的封闭提案中的用户使用请求参数来检查该路由是否属于某种类型,即产品,并返回404而不是403。也许可以将其应用于您的用例中,请检查在这里。希望我已经彻底了,也许会有所帮助。
In
app\Exceptions\Handler.php
in therender()
method you can define what should be done whenX
Exception is thrown. That being said, adding below piece of code should do the trick for you:What it does is basically checking if the Exception that is thrown is an AuthorizationException (which policies in Laravel throw) and if that is the case, throw a new NotFoundHttpException (
404
). This will however change any and all AuthorizationExceptions to a 404, which is probably not wanted behaviour.Update:
After digging I found a closed proposal for returning 404.
Personally I feel that a policy should not return anything but a 403 status code, since that is the correct code, something is forbidden. Returning a 404 would not be correct since the policy does not handle X resource not found.
If you'd really want you could change the
Handler.php
. I feel like this is not the correct way to use policies however, but that's beside the point.A user in above mentioned closed proposel used request parameters to check if the route belonged to a certain type, i.e. product and returned a 404 instead of 403. Maybe this can be applied to your use case aswell, check it out here. Hope I've been thorough and it maybe helps.