防止用户从非授权区域登录

Preventing users login from non authorized area

为了避免在用户尝试访问禁区时出现 403 错误并避免用户登录到该区域,我需要阻止用户在没有正确凭据的情况下登录。

让我解释得更好一点,假设我是X用户ROLE_USER,用户X可以访问前端但应该不能登录后端,就像我们有用户 YROLE_ADMIN 一样,用户 Y 可以登录后端但不能登录前端,明白吗?我怎样才能做到这一点?

假设我是角色为 'ROLE_ADMIN' 的用户 Adam。我无法登录到前端。

您应该简单地将此代码添加到您的控制器中:

  if( $this->get('security.context')->isGranted('YOUR ROLE') )
            return new Response('yea!');

因此,如果您想保护 BackendController 并允许使用 'ROLE_ADMIN' 登录用户,您应该添加此代码:

if( $this->get('security.context')->isGranted('ROLE_ADMIN') )
                return new Response('You are granted to see this site.');

此代码检查当前用户(我)是否具有角色 ROLE_ADMIN。如果你想检查用户是否有 'ROLE_ADMIN' AND 没有 'ROLE_USER' 只需添加:

$security = $this->get('security.context');
if( $security->isGranted('ROLE_ADMIN') && !$security->isGranted('ROLE_USER') )
                    return new Response('You are not granted to see this site.');

假设你的路线是correctly secured,你必须在你的树枝模板中隐藏/显示限制区域的链接。

来自Symfony2 doc :

{% if is_granted('ROLE_ADMIN') %}
    <a href="...">LogIntoBackend</a>
{% endif %}

相关:

  • Symfony2 security functions in Twig? How to check the user's role?
  • Symfony2: How to hide link in Twig based on permissions