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
Asked
Active
Viewed 1,070 times
0
-
What have you tried so far? – RajeshM May 27 '20 at 19:17
1 Answers
3
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

ustmaestro
- 1,233
- 12
- 20
-
Thanks a lot, the second approach works for me, really appreciate your response Sir – harsh shah May 28 '20 at 13:36