8
2

More than 3 years have passed since last update.

[CakePHP] AuthComponentのidentifyメソッドの中身の流れをざっくりと見ていく

Last updated at Posted at 2021-02-14

この記事ではCakePHPのAuthComponentのメソッドであるidentifyメソッドの中身の中身をざっくりと見ていきます。

identifyメソッドとは

リクエスト中の認証情報を使用してユーザーを識別するために、 $this->Auth->identify() を 手動で呼ぶ必要があります。

ユーザーを認証する際には、設定されている認証オブジェクトを設定された順にチェックしていきます。 あるオブジェクトでユーザーが識別できたら、以降のオブジェクトはチェックされません。

cakephp Bookより

注意

  • versionは3.9.6です
  • AuthComponentは4.0から非推奨です
  • あくまでも流れなので詳しく知りたい方はソースコードを追ってみてください

コード

  public function identify()
    {
        $this->_setDefaults();

        if (empty($this->_authenticateObjects)) {
            $this->constructAuthenticate();
        }
        foreach ($this->_authenticateObjects as $auth) {
            $result = $auth->authenticate(
                $this->getController()->getRequest(),
                $this->getController()->getResponse()
            );
            if (!empty($result)) {
                $this->_authenticationProvider = $auth;
                $event = $this->dispatchEvent('Auth.afterIdentify', [$result, $auth]);
                if ($event->getResult() !== null) {
                    return $event->getResult();
                }

                return $result;
            }
        }

        return false;
    }

まず3行目の

  $this->_setDefaults();

これは認証方法やログイン時のアクションメソッド等で特に指定が無ければデフォルトの設定を適用します。(例えば認証方法のデフォルトはFormオブジェクトでの認証となります)

次に5~7行目

if (empty($this->_authenticateObjects)) {
     $this->constructAuthenticate();
   }

ここで実際に認証に使うオブジェクトが_authenticateObjectsプロパティにセットされていなかった場合に認証オブジェクトを_authenticateObjectsにセットします。(_authenticateObjectsプロパティにはBaseAuthenticate抽象クラスを継承したインスタンスが入ります)

8行目

foreach ($this->_authenticateObjects as $auth) {

認証オブジェクトが入ったarrayをループします(認証方法が複数存在する可能性もあるのでループ処理をして一個ずつ認証オブジェクトを試します)

9~12行目

$result = $auth->authenticate(
                $this->getController()->getRequest(),
                $this->getController()->getResponse()
            );

ここで認証オブジェクトにリクエストとレスポンスのオブジェクトを渡し認証結果を受け取ります。

13~22行目

if (!empty($result)) {
        $this->_authenticationProvider = $auth;
        $event = $this->dispatchEvent('Auth.afterIdentify', [$result, $auth]);
            if ($event->getResult() !== null) {
                return $event->getResult();
            }

        return $result;

そして認証が成功した場合にどの認証方法で認証されたのかを_authenticationProviderプロパティに認証に使ったオブジェクトを代入し、その後Auth.afterIdentifyイベントを発行し、リスナーがある場合はその結果を返し無い場合は認証オブジェクトから返された結果をそのまま返します。

return false;

そして上記の処理で認証ができなかった場合はfalse, 認証失敗になります。

以上です。

なにか間違いや修正した方がいいことがあればご指摘をお願い致します。

8
2
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
8
2