title: Cakephp 3 Redirect when session expires
body: <p>I use the AuthComponent and I want when the session expires and the user press a link or refreshes, to redirect him on the login page.</p>
  <p>However for some actions I don't want above redirect, even if user is logged out, as they are used as an API by another application also.</p>
  <p>For example, I want to allow the 'view' action for logged-out users, but redirect the 'index' action.</p>
  <p>My AppController.php is:</p>
  <pre><code>$this-&gt;loadComponent('Auth', [
              'authorize' =&gt; [
                  'Acl.Actions' =&gt; ['actionPath' =&gt; 'controllers/']
              ],
              'authenticate' =&gt; [
                  'Form' =&gt; [
                      'fields' =&gt; [
                          'username' =&gt; 'username',
                          'password' =&gt; 'password'
                      ]
                  ]
              ],
              'loginAction' =&gt; [
                  'plugin' =&gt; false,
                  'controller' =&gt; 'Users',
                  'action' =&gt; 'login'
              ],
              'loginRedirect' =&gt; [
                  'controller' =&gt; 'Pages',
                  'action'     =&gt; 'index',
                  'plugin'     =&gt; 'Pages'
              ],
              'logoutRedirect' =&gt; [
                  'plugin' =&gt; false,
                  'controller' =&gt; 'Users',
                  'action'     =&gt; 'login'
              ],
  
          ]);
  </code></pre>
  <p>If I add below, 'index' is also working if user is logged-out, even though it should be in deny state.</p>
  <p>MyController.php</p>
  <pre><code> public function beforeFilter(\Cake\Event\Event $event)
      {
      $this-&gt;Auth-&gt;allow('view');
  </code></pre>
  <p>The only way I managed to do what I want is to add it in the controller action as:</p>
  <p>MyController.php</p>
  <pre><code>public function index()
      {
          
          if (empty($this-&gt;auth_user['username'])) {
              return $this-&gt;redirect($this-&gt;Auth-&gt;logout());
          }
  </code></pre>
  <p>Is there a better way to do this?</p>