LoginSignup
35
36

More than 5 years have passed since last update.

CakePHPのAuthコンポーネントで手動|自動ログインの落とし穴

Last updated at Posted at 2014-07-17

CakePHPでは、認証はAuthコンポーネントでユーザ登録&ログインを行うと超便利。だけど、ログイン処理を手動(自動)で実行したいっていうときには、ちょっとハマったポイントがあったのでメモ。

前提

CakePHP2.x

普通のログイン画面→認証の流れ

public function login() {
    if ($this->request->is('post')) {
        if ($this->Auth->login()) {
            return $this->redirect($this->Auth->redirectUrl());
        } else {
            $this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
       }
    }
}

まぁ、マニュアルにもある通り、普通にログイン画面→認証っていう手順なら、これ。POSTされたID/PWを読み取って、照合してくれる。

参考 : http://book.cakephp.org/2.0/ja/core-libraries/components/authentication.html#id5

ID/PWを指定してログインしてみる

でも、そういう手順を踏まずに、指定のID/PWで、好きなタイミングの時にログイン認証したい。$this->Auth->login()にパラメータ渡せばいけるかな…?つーわけで、このコード。

public function login() {
        $data = array(
            'username' => 'hoge',
            'password' => 'piyo'
        );
        if ($this->Auth->login($data)) {
            return $this->redirect($this->Auth->redirectUrl());
        }
    }
}

いけてる…風?と思いきや、なんかおかしい。AuthComponent本体を見てみる。

/lib/Cake/Controller/Component/AuthComponent.php
public function login($user = null) {
    $this->_setDefaults();

    if (empty($user)) {
        $user = $this->identify($this->request, $this->response);
    }
    if ($user) {
        $this->Session->renew();
        $this->Session->write(self::$sessionKey, $user);
    }
    return $this->loggedIn();
}

こんなかんじで、ユーザデータを渡せば、ログイン認証してくれる風になってるんだけど、よく見ると、単に渡されたデータをセッションに保存して、突っ返しているだけ…。正しくないパスワードを渡したってエラーにもならない。

マニュアルを良く見ると、

1.3 の $this->Auth->login($this->data) では、ユーザの識別を試みて成功したときのみログインが行われましたが、 2.x では $this->Auth->login($this->request->data) でなにが POST されたのだとしてもログインを行います。

2.xでは、なにやってもログインされる…。怖い。

手動でログインする正しい方法?

これが正しいかはわからないけど、要はPOSTしているふうに見せかければいいのでは。

public function login() {
        $this->request->data = array(
            'username' => 'hoge',
            'password' => 'piyo'
        );
        if ($this->Auth->login()) {
            return $this->redirect($this->Auth->redirectUrl());
        }
    }
}

$this->request->dataにパラメータを放り込んであげる。これで正しく認証できた。

35
36
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
35
36