2012-11-30 121 views
0

我正在使用zend framework-2做項目。我想限制通過URL訪問某些Web目錄(如果用戶沒有登錄)。如果用戶嘗試登錄,我需要重定向登錄頁面。這是我所做的(粗略的想法不是代碼)。我想限制通過URL訪問某些Web目錄

AuthController

if(username and password ok){ 
    setcookie('username', $username); 
    setcookie('password', $password); 

    //redirect to AlbumController indexAction 
    return $this->redirect()->toRoute('album', array('controller' => 'album', 'action' => 'index')); 
    } 

左右的時間內AlbumControoler我加入這個代碼

public function indexAction() 
{   
    if(isset ($_COOKIE['username']) && isset ($_COOKIE['password'])){ 
     //some codes 
    } 
    else{ 
     //if user not logged redirect to loogin page 
     return $this->redirect()->toRoute('auth', array('controller' => 'auth', 'action' => 'index')); 
    } 
} 

所以如果我用這種方式,我需要每一個動作上面添加代碼。所以我的問題是這樣好嗎?或者是他們簡單的方法來做到這一點?

+0

千萬不要使用用戶名/密碼格式的Cookies。不僅可以手動創建Cookie(我可以輕鬆訪問您的網絡應用程序),但它們也是這樣的巨大安全風險!查看[ZfcUser] [1]和[ZfcAcl] [2] [1]:https://github.com/ZF-Commons/ZfcUser [2]:https://github.com/ZF-Commons/ZfcAcl – Sam

+0

@Sam可以使用會話而不是cookies – user1784592

+0

您需要了解差異。看到以下問題的一些見解:http://stackoverflow.com/questions/356562/web-authentication-state-session-vs-cookie-vs和就ZF2而言,上述模塊將爲你做相當多的事情;) – Sam

回答

0

至於實際的問題,你可以在你的控制器構造做...像這樣的答案...

namespace Application\Controller; 

use Zend\Mvc\Controller\AbstractActionController; 
use Zend\View\Model\ViewModel; 

class IndexController extends AbstractActionController { 

    public function __construct() { 
     $session = new \Zend\Session\Container('auth'); 
     if (!isset($session->name) || !is_string($session->name)) { 
      echo "The following is not set:".$session->name; 
      header('Location: /user/login'); 
      exit(); 
     } 
    } 

但由於以前的海報悉餅乾真的不好用的東西喜歡這個。這是一個非常通用的例子,儘管exit();部分在這個意義上非常重要,因爲您希望殺死腳本以防止用戶在其瀏覽器中轉義時顯示任何數據。出口();將基本上消滅並且不顯示任何東西。

相關問題