Yii2 Yii::$app->user->identity->id returns an error instead of redirecting to login page
<p>in my behaviours I have specified that <code>actionList</code> can only be viewed by authenticated users.</p>

<pre><code>$behaviors [ 'access' ] = [
    'class' =&gt; AccessControl::className(),
    'rules' =&gt; [
        [
            'actions' =&gt; [ 'list' ],
            'allow'   =&gt; ['@'],
        ]
    ],
];
</code></pre>

<p>In <code>actionList</code> I'm getting the <code>user_id</code>:</p>

<pre><code>public function actionList() {
    $user_id  = \Yii::$app-&gt;user-&gt;identity-&gt;id;
    return $this-&gt;render( 'list' );
}
</code></pre>

<p>All good, but if you go to this action when not logged in, you get an error: </p>

<blockquote>
  <p>PHP Notice – yii\base\ErrorException</p>
  
  <p>Trying to get property of non-object</p>
</blockquote>

<p>Makes sense, I'm not logged in so I don't have a user id, but why does the code go that far? If I comment the <code>$user_id  = \Yii::$app-&gt;user-&gt;identity-&gt;id;</code> out, I get redirected to the login page, which is the expected behaviour. I don't think I should have to do yet another check to see if someone is logged in in the action itself, shouldn't that be handled by the <code>behaviours['access']</code> beforehand?</p>