I have a yii2 advanced project with many controllers, I want only some controllers to be accessible by users and block access to other controllers. Using access control I can set rules for actions but not controllers, any suggestion please
There are few type of configurations:
1) Block access to whole app (ak backend) with main config:
// ../config/main.php
return [
// ...
'components' => [
// ...
],
'as access' => [
'class' => yii\filters\AccessControl::class,
'except' => ['site/error', 'site/login', 'site/logout'],
'rules' => [
['allow' => true, 'roles' => ['@']],
],
],
];
2) Block access to specific controllers by extending an abstract controller class
use yii\filters\AccessControl;
use yii\web\Controller;
/**
* AbstractSecured controller
*/
abstract class AbstractSecuredController extends Controller
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::class,
// ...
// rules
]
];
}
}
Now you can extend this controller in your controllers
use yii\helpers\ArrayHelper;
/**
* MyNonPublic controller
*/
class MyNonPublicController extends AbstractSecuredController
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return ArrayHelper::merge(
parent::behaviors(),
[
// ...
// controller specific behaviors
// you can even rewrite access behavior config
]
);
}
}
3) You can also config ACL