Search code examples
restaccess-controlyii2

Yii2 rest controller's AccessControl filter redirects to login page


ApiController:

<?php
namespace frontend\controllers;

use Yii;
use yii\rest\Controller;
use yii\filters\AccessControl;

/**
 * API
 */

class ApiController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    public function actionTest()
    {
        echo 'here';
    }
}

When I open /api/test in browser AccessControl redirects to the login page. How to show json formatted error with 403 status code?

Thanks!


Solution

  • you should add denyCallback to change this behavior:

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
                'denyCallback' => function ($rule, $action) {
                    throw new \yii\web\ForbiddenHttpException('You are not allowed to access this page');
                }
            ],
        ];
    }