2015-02-05 54 views
1

为了避免当用户尝试访问禁止区域时出现403错误并且避免用户登录到该区域,我需要防止用户登录,如果没有正确的凭据。阻止用户从非授权区域登录

让我解释一下好一点,假设我是X用户ROLE_USER,用户X可以访问前端,但不应该能够登录到后台,就如同我们的用户YROLE_ADMIN,用户Y可能登录后端,但不在前端,了解我吗?我怎么能做到这一点?

回答

1

让我们假设我是角色为'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.');