2015-02-05 53 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.');