authorization.md 8.34 KB
Newer Older
1 2 3 4 5 6 7 8 9
Authorization
=============

Authorization is the process of verifying that user has enough permissions to do something. Yii provides several methods
of controlling it.

Access control basics
---------------------

10
Basic access control is very simple to implement using [[yii\filters\AccessControl]]:
11 12 13 14

```php
class SiteController extends Controller
{
15 16 17 18
    public function behaviors()
    {
        return [
            'access' => [
19
                'class' => \yii\filters\AccessControl::className(),
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
                'only' => ['login', 'logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['login', 'signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }
    // ...
37 38 39 40
```

In the code above we're attaching access control behavior to a controller. Since there's `only` option specified, it
will be applied to 'login', 'logout' and 'signup' actions only. A set of rules that are basically options for
41
[[yii\filters\AccessRule]] reads as follows:
42 43 44 45 46 47 48

- Allow all guest (not yet authenticated) users to access 'login' and 'signup' actions.
- Allow authenticated users to access 'logout' action.

Rules are checked one by one from top to bottom. If rule matches, action takes place immediately. If not, next rule is
checked. If no rules matched access is denied.

49
[[yii\filters\AccessRule]] is quite flexible and allows additionally to what was demonstrated checking IPs and request method
50 51 52 53 54
(i.e. POST, GET). If it's not enough you can specify your own check via anonymous function:

```php
class SiteController extends Controller
{
55 56 57 58
    public function behaviors()
    {
        return [
            'access' => [
59
                'class' => \yii\filters\AccessControl::className(),
60 61 62 63 64 65 66 67 68
                'only' => ['special-callback'],
                'rules' => [
                    [
                        'actions' => ['special-callback'],
                        'allow' => true,
                        'matchCallback' => function ($rule, $action) {
                            return date('d-m') === '31-10';
                        }
                    ],
69 70
```

71 72 73
And the action:

```php
74 75 76 77 78 79
    // ...
    // Match callback called! This page can be accessed only each October 31st
    public function actionSpecialCallback()
    {
        return $this->render('happy-halloween');
    }
80 81
```

82 83 84 85 86 87 88 89
Sometimes you want a custom action to be taken when access is denied. In this case you can specify `denyCallback`.

Role based access control (RBAC)
--------------------------------

Role based access control is very flexible approach to controlling access that is a perfect match for complex systems
where permissions are customizable.

90 91
### Using file-based config for RBAC

92
In order to start using it some extra steps are required. First of all we need to configure `authManager` application
93
component in application config file (`web.php` or `main.php` depending on template you've used):
94 95

```php
96 97 98 99 100 101 102 103 104 105 106 107 108 109
'authManager' => [
    'class' => 'app\components\PhpManager',
    'defaultRoles' => ['guest'],
],
```

Often use role is stored in the same database table as other user data. In this case we may defined it by creating our
own component (`app/components/PhpManager.php`):

```php
<?php
namespace app\components;

use Yii;
110

111 112 113 114 115 116 117 118 119 120 121
class PhpManager extends \yii\rbac\PhpManager
{
    public function init()
    {
        parent::init();
        if (!Yii::$app->user->isGuest) {
            // we suppose that user's role is stored in identity
            $this->assign(Yii::$app->user->identity->id, Yii::$app->user->identity->role);
        }
    }
}
122 123
```

Alexander Makarov committed
124 125 126 127 128 129
Now create custom rule class:

```php
namespace app\rbac;

use yii\rbac\Rule;
armab committed
130
use Yii;
Alexander Makarov committed
131 132 133

class NotGuestRule extends Rule
{
Aleksandr Zelenin committed
134 135
    public $name = 'notGuestRule';

Alexander Makarov committed
136 137 138 139 140 141 142
    public function execute($params, $data)
    {
        return !Yii::$app->user->isGuest;
    }
}
```

143 144 145 146 147
Then create permissions hierarchy in `@app/data/rbac.php`:

```php
<?php
use yii\rbac\Item;
Alexander Makarov committed
148 149 150
use app\rbac\NotGuestRule;

$notGuest = new NotGuestRule();
151 152

return [
Alexander Makarov committed
153
    'rules' => [
Alexander Makarov committed
154
        $notGuest->name => serialize($notGuest),
155
    ],
Alexander Makarov committed
156 157
    'items' => [
        // HERE ARE YOUR MANAGEMENT TASKS
Aleksandr Zelenin committed
158 159 160 161
        'manageThing0' => ['type' => Item::TYPE_OPERATION, 'description' => '...', 'ruleName' => null, 'data' => null],
        'manageThing1' => ['type' => Item::TYPE_OPERATION, 'description' => '...', 'ruleName' => null, 'data' => null],
        'manageThing2' => ['type' => Item::TYPE_OPERATION, 'description' => '...', 'ruleName' => null, 'data' => null],
        'manageThing3' => ['type' => Item::TYPE_OPERATION, 'description' => '...', 'ruleName' => null, 'data' => null],
Alexander Makarov committed
162 163 164 165 166

        // AND THE ROLES
        'guest' => [
            'type' => Item::TYPE_ROLE,
            'description' => 'Guest',
Aleksandr Zelenin committed
167 168
            'ruleName' => null,
            'data' => null
Alexander Makarov committed
169
        ],
170

Alexander Makarov committed
171 172 173 174 175 176 177 178
        'user' => [
            'type' => Item::TYPE_ROLE,
            'description' => 'User',
            'children' => [
                'guest',
                'manageThing0', // User can edit thing0
            ],
            'ruleName' => $notGuest->name,
Aleksandr Zelenin committed
179
            'data' => null
180 181
        ],

Alexander Makarov committed
182 183 184 185 186 187 188
        'moderator' => [
            'type' => Item::TYPE_ROLE,
            'description' => 'Moderator',
            'children' => [
                'user',         // Can manage all that user can
                'manageThing1', // and also thing1
            ],
Aleksandr Zelenin committed
189 190
            'ruleName' => null,
            'data' => null
191 192
        ],

Alexander Makarov committed
193 194 195 196 197 198 199
        'admin' => [
            'type' => Item::TYPE_ROLE,
            'description' => 'Admin',
            'children' => [
                'moderator',    // can do all the stuff that moderator can
                'manageThing2', // and also manage thing2
            ],
Aleksandr Zelenin committed
200 201
            'ruleName' => null,
            'data' => null
202 203
        ],

Alexander Makarov committed
204 205 206 207 208 209 210
        'godmode' => [
            'type' => Item::TYPE_ROLE,
            'description' => 'Super admin',
            'children' => [
                'admin',        // can do all that admin can
                'manageThing3', // and also thing3
            ],
Aleksandr Zelenin committed
211 212
            'ruleName' => null,
            'data' => null
213 214 215 216 217 218 219 220 221 222 223 224
        ],
    ],
];
```

Now you can specify roles from RBAC in controller's access control configuration:

```php
public function behaviors()
{
    return [
        'access' => [
225
            'class' => 'yii\filters\AccessControl',
226 227 228 229 230 231 232 233 234 235 236
            'except' => ['something'],
            'rules' => [
                [
                    'allow' => true,
                    'roles' => ['manageThing1'],
                ],
            ],
        ],
    ];
}
```
237

238
Another way is to call [[yii\web\User::checkAccess()]] where appropriate.
239

240 241 242 243 244 245
### Using DB-based storage for RBAC

Storing RBAC hierarchy in database is less efficient performancewise but is much more flexible. It is easier to create
a good management UI for it so in case you need permissions structure that is managed by end user DB is your choice.

In order to get started you need to configure database connection in `db` component. After it is done [get `schema-*.sql`
Qiang Xue committed
246
file for your database](https://github.com/yiisoft/yii2/tree/master/framework/rbac) and execute it.
247 248 249 250 251 252 253 254 255 256 257 258 259

Next step is to configure `authManager` application component in application config file (`web.php` or `main.php`
depending on template you've used):

```php
'authManager' => [
    'class' => 'yii\rbac\DbManager',
    'defaultRoles' => ['guest'],
],
```

TBD

260 261 262 263 264 265 266 267 268 269 270 271
### How it works

TBD: write about how it works with pictures :)

### Avoiding too much RBAC

In order to keep auth hierarchy simple and efficient you should avoid creating and using too much nodes. Most of the time
simple checks could be used instead. For example such code that uses RBAC:

```php
public function editArticle($id)
{
Alexander Makarov committed
272
  $article = Article::findOne($id);
273
  if (!$article) {
274
    throw new NotFoundHttpException;
275 276
  }
  if (!\Yii::$app->user->checkAccess('edit_article', ['article' => $article])) {
277
    throw new ForbiddenHttpException;
278 279 280 281 282 283 284 285 286 287
  }
  // ...
}
```

can be replaced with simpler code that doesn't use RBAC:

```php
public function editArticle($id)
{
Alexander Makarov committed
288
    $article = Article::findOne(['id' => $id, 'author_id' => \Yii::$app->user->id]);
289
    if (!$article) {
290
      throw new NotFoundHttpException;
291 292 293 294
    }
    // ...
}
```