2016-09-28 60 views
0

我需要過濾json請求並允許這些請求的基本身份驗證,同時只允許對html請求進行表單身份驗證。當我在過濾器中AppController.php我的初始化函數的要求:如何使用基本身份驗證進行json請求並使用CakePHP 3對html請求進行身份驗證?

if ($this->request->is('json')) { 
     $this->loadComponent('Auth', [ 
      'authorize' => ['Controller'], 
      'authenticate' => [ 
       'Basic' => [ 
        'fields' => ['username' => 'email', 'password' => 'password'], 
        'contain' => ['Districts'] 
       ] 
      ] 
     ]); 
    } else { 
     $this->loadComponent('Auth', [ 
      'authorize' => ['Controller'], 
      'authenticate' => [ 
       'Form' => [ 
        'fields' => ['username' => 'email', 'password' => 'password'], 
        'contain' => ['Districts'] 
       ] 
      ], 
      'loginAction' => [ 
       'controller' => 'Users', 
       'action' => 'login' 
      ], 
      'logoutRedirect' => [ 
       'controller' => 'Users', 
       'action' => 'login' 
      ] 
     ]); 
    } 

的JSON請求創建並存儲會話允許用戶再訪問網站的其餘部分,包括HTML請求,因爲它有一個授權會話。我試圖找出造成這種情況的原因,並最終發現必須明確聲明基本身份驗證方法的存儲介質爲「內存」。我將在下面的答案中發佈正確的代碼。

這個問題類似於這一個CakePHP的2:CakePHP form authentication for normal requests with basic authentication for JSON

回答

1

你必須明確地聲明,基本身份驗證使用內存作爲存儲介質,否則它會創建一個會話。這裏是正確的代碼:

if ($this->request->is('json')) { 
     $this->loadComponent('Auth', [ 
      'authorize' => ['Controller'], 
      'authenticate' => [ 
       'Basic' => [ 
        'fields' => ['username' => 'email', 'password' => 'password'], 
        'contain' => ['Districts'] 
       ] 
      ], 
      'storage' => 'Memory' 
     ]); 
    } else { 
     $this->loadComponent('Auth', [ 
      'authorize' => ['Controller'], 
      'authenticate' => [ 
       'Form' => [ 
        'fields' => ['username' => 'email', 'password' => 'password'], 
        'contain' => ['Districts'] 
       ] 
      ], 
      'loginAction' => [ 
       'controller' => 'Users', 
       'action' => 'login' 
      ], 
      'logoutRedirect' => [ 
       'controller' => 'Users', 
       'action' => 'login' 
      ] 
     ]); 
    } 
相關問題