I'm facing a problem where I've configured RBAC in Yii 2.0 but it does not work - meaning it dooes not prevent any of the pages from being loaded - even as guest.
This is in my web.php config (also in my console.php):
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
The migrations have completed successfully.
This is how behaviors() look like at the moment, but I tried many different ways.
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['error'],
'allow' => true,
//'roles' => ["?"],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
If I implement the behaviors() function in my controller, the framework starts doing some access-handling, but the goal of using a DB as I understand should be that the RBAC system takes over this responsibility - meaning I don't have to enable/disable every single action I write for every single role.
I have added a Role "Admin" and assigned a few of the available routes (actions) to it.
Then I assigned this role to my User name. In theory this should enable my login to access those specific routes but nothing else - instead, I can traverse the site however I please, no 403s whatsoever. (This is why I'm saying RBAC acts like it's non-existing.)
Any hints or tips are appreciated.
Thanks.
where is your authManager configuration located?
According to [yii2 guide]
If you are using yii2-basic-app template, there is a config/console.php configuration file where the authManager needs to be declared additionally to config/web.php. In case of yii2-advanced-app the authManager should be declared only once in common/config/main.php.
Update to this question, I just tried do rbac manually
My result
We must do conditional in every action like
...
public function actionAbout()
{
if (Yii::$app->user->can('ViewAbout')) {
echo "you may see view about";
} else {
echo "view about is prohibited";
}
// return $this->render('about');
}
...
If you want assign it in common way, you better use extension/module that handle authmanager (like yii2-admin, yii2-mimin, etc)
Hope this answer help
I have 2 applications: frontend and backend.
Users on frontend have role "client".
How do I disable access to the application backend users with "client" role. All other roles are allowed access. site/login on backend allow for all users.
I wrote the following code in my main.phpfile:
'as beforeRequest' => [
'class' => 'yii\filters\AccessControl',
'rules' => [
[
'allow' => true,
'controllers' => ['site'],
'actions' => ['login'],
'roles' => ['?'],
],
[
'allow' => false,
'roles' => ['client'],
],
],
'denyCallback' => function () {
return Yii::$app->response->redirect(['site/login']);
},
],
I have error: ERR_TOO_MANY_REDIRECTS in chrome.
From the guide 'roles' => ['?']:
matches a guest user (not authenticated yet)
Since the user is logged in they are stuck in a redirect loop caused by the second rule and the denyCallback i.e.
User is logged in but is of role client and is therefore not allowed.
Since user has been denied access, redirect to site/login.
See 1.
This can be fixed by omitting the roles element in your first rule:
If [role] is not set or empty, it means this rule applies to all roles.
HOWEVER THIS IS THE WRONG APPROACH
Users who are logged in but are of role client should be denied access to the backend. Sending them to login will not help since they are already logged in. The proper course of action is to send them to the frontend's error page.
Basically, i'm using a standard Yii2 set up. i have a login that allows a user to see links to files. the files are in a download folder.. but the page to see the links is only able to be seen if a user is "not guest." now, if anyone just copies the link to someone else, that other person will be able to download the file without being logged in. the files in question aren't being "paid for" BUT i am required to have people login before they are allowed to download them becuase of terms of service and other laws. can i dynamically create download links via php? at least check for "isGuest" and if isGuest = True then redirect to login page. how would i do that instead of just having a direct download link?
You can provide acces to an specific action to specific roles or users with AccessControl Class .
You can do something like this:
class DownloadController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => false,
'actions' => ['download'],
'roles' => ['?'],
],
],
],
];
}
// ...
}
'?' Role are the guest users.
You can add a check in your controller's action to validate if the user is logged in or not, using:
Yii::$app->user->getIsGuest();
Look at the documentation for more details: Yii2 web user
Forbid access for anyone to the file to direct download. You can do so with htaccess or by putting the download folder into yiis protected folder. Now you need a download action in a controller where you check if the user is guest or logged in. If ok, simply pass the file through from your filesystem and to the users browser. phps readfile can help you here.
I've been developing web apps using Yii 1.1.14 so far, but now it's time for an upgrade.
The company where I work has developed its own Access Control system, and I was really OK with it until I saw what it was really like... A combination of 8 tables in the database (not counting the users table), with a bunch of foreign keys.
1 table for controllers
1 table for the actions
1 table for the menu categories
1 table for types of users
And the other tables basically just connect 2 or 3 of those tables at a time.
It works well, but in my point of view it's highly time consuming to maintain all those tables, and at some point, when your application goes online, if it hits a certain amount of users it could get really slow. specially because 2 of those tables have the user's table primary key as foreign key.
So I've decided that, when I start developing on Yii 2, I'm going to start using RBAC, so I started looking for tutorials online... Only finding many different versions of the same code with author's role, and permissions for create or update posts.
I found a combination of 5 videos on Youtube, but they are about Yii 1 RBAC. They were helpful because I managed to understand most of RBAC's functionality, but I still have some doubts that I'll
enumerate below. And keep in mind that for this Access Control system I'm using the DBManager class.
My Doubts
Yii 1's RBAC used to have 3 tables: auth_assignment, auth_item and auth_item_child. Now in Yii 2 RBAC, a new table appears that is called auth_rule and I still don't understand what that specific table is doing there, how to use it or how to populate it.
I see that it's possible to restrict the user's access to some actions by using the controller's behavior method, and assigning access to some actions depending on the user's role, but when it comes to this I have to split my question into 2:
2.1. First: If you can just restrict the access to actions by setting it up in the behaviors method, then what's the use of saving permissions to the auth_item table?
2.2. Second: If you DO decide to control access according to permissions, then how exactly do you do it, because I find myself writing the following type of code inside of every function and I don't think using RBAC is supposed to be this tedious. There has to be another way.
public function actionView($id)
{
if(Yii::$app->user->can('view-users')){
return $this->render('view', [
'model' => $this->findModel($id),
]);
}else{
#Redirect to a custom made action that will show a view
#with a custom error message
$this->redirect(['//site/notauthorized']);
}
}
Because of the Access Control System that we use right now, when a user logs in, a complex query is executed that will end up returning an array that will be saved as a session variable, and will be used to create a menu with as many dropdownlists as menu categories, that the controllers that the user has access to belong to. How can this be done with RBAC?
I can only really answer 2.2 of your question, as 3 doesn't sound at all like something an RBAC should do. You could, however, get the information you needed from the rules table most likely, provided you followed a naming convention that matched your controllers or actions.
On to answering 2.2 though:
You can simply set the behavior like such:
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'actions' => ['view'],
'roles' => ['view-users'], //<-- Note, rule instead of role
],
]
]
}
This doesn't solve a different problem of 'view-own-users' style permissions, as this needs to inspect the ActiveRecord model (well, at least it does in my application). If You want to achieve this, take a look at my post in the Yii forums here:
http://www.yiiframework.com/forum/index.php/topic/60439-yii2-rbac-permissions-in-controller-behaviors/#entry269913
I use it in one of the simplest method,I use them in the behaviours of my controller.
public function behaviors()
{
return [
'access' => [
'class' => \yii\filters\AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['sysadmin'],
'actions' => ['index','view','update'],
],
[
'allow' => true,
'roles' => ['staff'],
'actions' => ['index','create','update','view'],
],
],
],
];
}
Here roles are the one created in the auth-item table in the database and they have been assigned for users in auth-assignment table. In the behaviours we just use it as above. In the above code sysadmin can have access to index, view and update action, whereas staff can have access to index,create, update and view action.
Yii2 needs a little setup when it comes to using RBAC under your controllers AccessControl. I got around it by making my own AccessRule file.
namespace app\components;
use Yii;
class AccessRule extends \yii\filters\AccessRule
{
protected function matchRole($user)
{
if (empty($this->roles)) {
return true;
}
foreach ($this->roles as $role) {
if(Yii::$app->authManager->checkAccess($user->identity->code, $role))
return true;
}
return false;
}
then in your controller u can use something like this:
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'ruleConfig' => [
'class' => 'app\components\AccessRule'
],
'rules' => [
[
'actions' => ['index', 'resource-type'],
'allow'=> true,
'roles' => ['admin'],
],
],
],
];
}
Where admin is defined as a auth_item and the user is in the auth_item_assignments.
As I have created a new Rbac system for yii2. you can direct permission for a action and action will show you are not authorisez for this action.
By this you find that you will only provide access for action that need to identify.
I uploaded my detail here you can find lot of solution here.
This is the best solution i could come up with when facing the need to filter access by permissions, it's bothersome but can be useful if you're trying to create roles in a productive enviroment and want to use rbac.
use yii\web\ForbiddenHttpException;
if(Yii::$app->user->can('view-users')){
return $this->render('view', [
'model' => $this->findModel($id),
]);
}else{
throw new ForbiddenHttpException('You dont have access to this site');
}
I'm using yii-powered app as backend of public API. I created controllers/ApiController class with actionTest method and trying to get some data by url domain.ltd/api/test without authorization by login/pass which usually need for another controllers (SiteController, for example). How can I do this?
I think there are few variants:
Setup route /api/* for guest access using authManager (?)
Something magic with UserIdentity class...
To allow anyone to access that page, just specify that in rules of controller (similar to login page, as you can access it without logging in)
public function accessRules()
{
return [
[
'allow',
'actions' => ['test'],
'users' => ['*'],
],
['deny', // deny all users
'users' => ['*'],
],
];
}