2016-11-10 23 views
0

我正在使用this JWTAuth adapter在我的CakePHP 2.8應用程序中使用JWT驗證而不是基於cookie的驗證。它的效果很好,除了一個hitch:在使用自定義驗證適配器時檢查CakePHP上的登錄用戶信息

通常對於我的REST端點之一,我可以使用$this->Auth->user("id")來獲取當前登錄的用戶的ID。

當我嘗試使用$this->Auth->allow()的非成員訪問控制器操作時,會發生問題。如果我這樣做,在控制器中使用$this->Auth->loggedIn()將返回false,這意味着我無法爲登錄用戶添加其他邏輯。

當使用標準cookie認證:

  • $this->Auth->user('id')Controller::beforeFilter()可用。
  • $this->Auth->loggedIn()true in Controller::beforeFilter()
  • $this->Auth->user('id')可用於控制器操作,公開 和僅限會員。
  • $this->Auth->loggedIn()true在控制器動作,公共 和成員只。

當使用智威湯遜AUTH:

  • $this->Auth->user('id')Controller::beforeFilter()null
  • $this->Auth->loggedIn()false in Controller::beforeFilter()
  • $this->Auth->user('id')僅在成員控制器可用的動作,並在公共控制器動作null
  • $this->Auth->loggedIn()true在會員專用控制器動作,並false在公共控制器動作。

是否有任何方法可以獲得Auth,以包含JWTAuth組件在由$this->Auth->allow()公開的操作中所返回的信息?

實施例控制器在這裏:

public function visible(){ 
    // This will always be false, even if a valid JWT token is sent 
    $this->set("loggedIn", $this->Auth->loggedIn()); 
} 

public function members_only(){ 
    // This will be unavailable if not logged in, and a true if logged in 
    $this->set("loggedIn", $this->Auth->loggedIn()); 
} 

public function beforeFilter($options = array()){ 
    parent::beforeFilter(); 

    $this->Auth->allow("visible"); 
} 

而對於參考,我的AppController ::組件陣列;

public $components = array(
    'DebugKit.Toolbar', 
    'Auth' => array(
     'authorize' => array(
      'Actions' => array(
       'actionPath' => 'controllers' 
      ), 
     ), 
     'authenticate' => array(
      'Form' => array(
       'fields' => array('username' => 'email'), 
       'contain' => array(
        'UserProfile', 
       ) 
      ), 
      'JwtAuth.JwtToken' => array(
       'fields' => array(
        'username' => 'email', 
        'token' => 'password', 
       ), 
       'header' => 'AuthToken', 
       'userModel' => 'User', 
      ), 
     ), 
     'unauthorizedRedirect' => false 
    ), 
    "Acl", 
    "RequestHandler", 
    "Session" 
); 

回答

1

對於無狀態適配器認證處理是在AuthComponent::startup() triggerd。組件的startup()方法後Controller::beforeFilter()運行,這就是爲什麼AuthComponent::user()不返回任何信息。

因爲當用戶通過驗證身份信息其他適配器被存儲在會話。獲取該信息不需要任何驗證過程,這就是爲什麼AuthComponent::user()在標準的基於cookie的驗證的情況下爲您提供用戶信息的原因。

+0

只想在CakePHP 3.x中提到,AuthComponent可以配置爲在控制器的'beforeFilter()'之前運行的'initialize()'方法中運行認證過程。 – ADmad

相關問題