php 如何在 Symfony2 中抛出 403 异常?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21932229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I throw a 403 exception in Symfony2?
提问by Gottlieb Notschnabel
I am doing a check if there is a specific token in my request URI and throw a Symfony\Component\Security\Core\Exception\AccessDeniedExceptionif there is no token or the token is wrong.
我正在检查我的请求 URI 中是否有特定的令牌,Symfony\Component\Security\Core\Exception\AccessDeniedException如果没有令牌或令牌错误,则抛出一个。
if(!isset($token) && $token != 'whatever') {
throw new AccessDeniedException('No token given or token is wrong.');
}
But when I use this AccessDeniedException, Symfony2 simply redirects to the login page. Instead, I would like to have a dedicated 403 error page (I already created app/Resources/TwigBundle/views/Exceptions/error403.html.twigfile).
但是当我使用它时AccessDeniedException,Symfony2 只是重定向到登录页面。相反,我想要一个专门的 403 错误页面(我已经创建了app/Resources/TwigBundle/views/Exceptions/error403.html.twig文件)。
What would I have to change in order to achieve this? Do I have to use a PHP native Exception? But how can I tell to pass a 403 error code?
为了实现这一目标,我必须改变什么?我必须使用 PHP 原生异常吗?但是我怎么知道要传递 403 错误代码呢?
Does Symfony2 maybe have a specific 403-Exception which doesn't simply redirect to login?
Symfony2 是否可能有一个特定的 403-Exception 不简单地重定向到登录?
回答by Cerad
Throw Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException.
扔Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException。
That will bypass the security system and give you a 403 response which in turn will get picked up by the twig exception listener.
这将绕过安全系统并为您提供 403 响应,该响应将被树枝异常侦听器接收。
回答by COil
As of Symfony 2.6 you can use the following controller shortcut that will trigger the good exception for you:
从 Symfony 2.6 开始,您可以使用以下控制器快捷方式来触发良好的异常:
return $this->denyAccessUnlessGranted('ROLE_EDIT', $item, 'You cannot edit this item.');

