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


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"没有"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.');

假设您的路由得到了正确的保护,则必须在分支模板中隐藏/显示到受限区域的链接。

来自Symfony2文档:

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

相关:

  • Twig中的Symfony2安全功能?如何检查用户';的角色
  • Symfony2:如何根据权限在Twig中隐藏链接