/
authorization.texy
295 lines (212 loc) Β· 10.7 KB
/
authorization.texy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
Access Control (Authorization)
******************************
.[perex]
Authorization determines whether a user has sufficient privileges, for example, to access a specific resource or to perform an action. Authorization assumes previous successful authentication, ie that the user is logged in.
β [Installation and requirements |@home#Installation]
In the examples, we will use an object of class [api:Nette\Security\User], which represents the current user and which you get by passing it using [dependency injection |dependency-injection:passing-dependencies]. In presenters simply call `$user = $this->getUser()`.
.[warning]
In version 3.0 the interfaces still had the `I` prefix, so the names were `Nette\Security\IUserStorage`, `IAuthenticator` and `IAuthorizer` etc. Furthermore, the `Nette\Security\SimpleIdentity` class was called `Nette\Security\dentity`.
For very simple websites with administration, where user rights are not distinguished, it is possible to use the already known method as an authorization criterion `isLoggedIn()`. In other words: once a user is logged in, he has permissions to all actions and vice versa.
```php
if ($user->isLoggedIn()) { // is user logged in?
deleteItem(); // if so, he may delete an item
}
```
Roles
-----
The purpose of roles is to offer a more precise permission management and remain independent on the user name. As soon as user logs in, he is assigned one or more roles. Roles themselves may be simple strings, for example, `admin`, `member`, `guest`, etc. They are specified in the second argument of `SimpleIdentity` constructor, either as a string or an array.
As an authorization criterion, we will now use the method `isInRole()`, which checks whether the user is in the given role:
```php
if ($user->isInRole('admin')) { // is the admin role assigned to the user?
deleteItem(); // if so, he may delete an item
}
```
As you already know, logging the user out does not erase his identity. Thus, method `getIdentity()` still returns object `SimpleIdentity`, including all granted roles. The Nette Framework adheres to the principle of "less code, more security", so when you are checking roles, you do not have to check whether the user is logged in too. Method `isInRole()` works with **effective roles**, ie if the user is logged in, roles assigned to identity are used, if he is not logged in, an automatic special role `guest` is used instead.
Authorizator
------------
In addition to roles, we will introduce the terms resource and operation:
- **role** is a user attribute - for example moderator, editor, visitor, registered user, administrator, ...
- **resource** is a logical unit of the application - article, page, user, menu item, poll, presenter, ...
- **operation** is a specific activity, which user may or may not do with *resource* - view, edit, delete, vote, ...
An authorizer is an object that decides whether a given *role* has permission to perform a certain *operation* with specific *resource*. It is an object implementing the [api:Nette\Security\Authorizator] interface with only one method `isAllowed()`:
```php
class MyAuthorizator implements Nette\Security\Authorizator
{
public function isAllowed($role, $resource, $operation): bool
{
if ($role === 'admin') {
return true;
}
if ($role === 'user' && $resource === 'article') {
return true;
}
// ...
return false;
}
}
```
We add the authorizator to the configuration [as a service |dependency-injection:services] of the DI container:
```neon
services:
- MyAuthorizator
```
And the following is an example of use. Note that this time we call the method `Nette\Security\User::isAllowed()`, not the authorizator's one, so there is not first parameter `$role`. This method calls `MyAuthorizator::isAllowed()` sequentially for all user roles and returns true if at least one of them has permission.
```php
if ($user->isAllowed('file')) { // is user allowed to do everything with resource 'file'?
useFile();
}
if ($user->isAllowed('file', 'delete')) { // is user allowed to delete a resource 'file'?
deleteFile();
}
```
Both arguments are optional and their default value means *everything*.
Permission ACL
--------------
Nette comes with a built-in implementation of the authorizer, the [api:Nette\Security\Permission] class, which offers a lightweight and flexible ACL (Access Control List) layer for permission and access control. When we work with this class, we define roles, resources, and individual permissions. And roles and resources may form hierarchies. To explain, we will show an example of a web application:
- `guest`: visitor that is not logged in, allowed to read and browse public part of the web, ie. read articles, comment and vote in polls
- `registered`: logged-in user, which may on top of that post comments
- `admin`: can manage articles, comments and polls
So we have defined certain roles (`guest`, `registered` and `admin`) and mentioned resources (`article`, `comments`, `poll`), which the users may access or take actions on (`view`, `vote`, `add`, `edit`).
We create an instance of the Permission class and define **roles**. It is possible to use the inheritance of roles, which ensures that, for example, a user with a role `admin` can do what an ordinary website visitor can do (and of course more).
```php
$acl = new Nette\Security\Permission;
$acl->addRole('guest');
$acl->addRole('registered', 'guest'); // 'registered' inherits from 'guest'
$acl->addRole('admin', 'registered'); // and 'admin' inherits from 'registered'
```
We will now define a list of **resources** that users can access:
```php
$acl->addResource('article');
$acl->addResource('comment');
$acl->addResource('poll');
```
Resources can also use inheritance, for example, we can add `$acl->addResource('perex', 'article')`.
And now the most important thing. We will define between them **rules** determining who can do what:
```php
// everything is denied now
// let the guest view articles, comments and polls
$acl->allow('guest', ['article', 'comment', 'poll'], 'view');
// and also vote in polls
$acl->allow('guest', 'poll', 'vote');
// the registered inherits the permissions from guesta, we will also let him to comment
$acl->allow('registered', 'comment', 'add');
// the administrator can view and edit anything
$acl->allow('admin', $acl::ALL, ['view', 'edit', 'add']);
```
What if we want to **prevent** someone from accessing a resource?
```php
// administrator cannot edit polls, that would be undemocractic.
$acl->deny('admin', 'poll', 'edit');
```
Now when we have created the set of rules, we may simply ask the authorization queries:
```php
// can guest view articles?
$acl->isAllowed('guest', 'article', 'view'); // true
// can guest edit an article?
$acl->isAllowed('guest', 'article', 'edit'); // false
// can guest vote in polls?
$acl->isAllowed('guest', 'poll', 'vote'); // true
// may guest add comments?
$acl->isAllowed('guest', 'comment', 'add'); // false
```
The same applies to a registered user, but he can also comment:
```php
$acl->isAllowed('registered', 'article', 'view'); // true
$acl->isAllowed('registered', 'comment', 'add'); // true
$acl->isAllowed('registered', 'comment', 'edit'); // false
```
The administrator can edit everything except polls:
```php
$acl->isAllowed('admin', 'poll', 'vote'); // true
$acl->isAllowed('admin', 'poll', 'edit'); // false
$acl->isAllowed('admin', 'comment', 'edit'); // true
```
Permissions can also be evaluated dynamically and we can leave the decision to our own callback, to which all parameters are passed:
```php
$assertion = function (Permission $acl, string $role, string $resource, string $privilege): bool {
return /* ... */;
};
$acl->allow('registered', 'comment', null, $assertion);
```
But how to solve a situation where the names of roles and resources are not enough, ie we would like to define that, for example, a role `registered` can edit a resource `article` only if it is its author? We will use objects instead of strings, the role will be the object [api:Nette\Security\Role] and the source [api:Nette\Security\Resource]. Their methods `getRoleId()` resp. `getResourceId()` will return the original strings:
```php
class Registered implements Nette\Security\Role
{
public $id;
public function getRoleId(): string
{
return 'registered';
}
}
class Article implements Nette\Security\Resource
{
public $authorId;
public function getResourceId(): string
{
return 'article';
}
}
```
And now let's create a rule:
```php
$assertion = function (Permission $acl, string $role, string $resource, string $privilege): bool {
$role = $acl->getQueriedRole(); // object Registered
$resource = $acl->getQueriedResource(); // object Article
return $role->id === $resource->authorId;
};
$acl->allow('registered', 'article', 'edit', $assertion);
```
The ACL is queried by passing objects:
```php
$user = new Registered(/* ... */);
$article = new Article(/* ... */);
$acl->isAllowed($user, $article, 'edit');
```
A role may inherit form one or more other roles. But what happens, if one ancestor has certain action allowed and the other one has it denied? Then the *role weight* comes into play - the last role in the array of roles to inherit has the greatest weight, first one the lowest:
```php
$acl = new Nette\Security\Permission;
$acl->addRole('admin');
$acl->addRole('guest');
$acl->addResource('backend');
$acl->allow('admin', 'backend');
$acl->deny('guest', 'backend');
// example A: role admin has lower weight than role guest
$acl->addRole('john', ['admin', 'guest']);
$acl->isAllowed('john', 'backend'); // false
// example B: role admin has greater weight than role guest
$acl->addRole('mary', ['guest', 'admin']);
$acl->isAllowed('mary', 'backend'); // true
```
Roles and resources can also be removed (`removeRole()`, `removeResource()`), rules can also be reverted (`removeAllow()`, `removeDeny()`). The array of all direct parent roles returns `getRoleParents()`. Whether two entities inherit from each other returns `roleInheritsFrom()` and `resourceInheritsFrom()`.
Add as a Service
----------------
We need to add the ACL created by us to the configuration as a service so that it can be used by the object `$user`, ie so that we can use in code for example `$user->isAllowed('article', 'view')`. For this purpose, we will write a factory for it:
```php
namespace App\Model;
class AuthorizatorFactory
{
public static function create(): Nette\Security\Permission
{
$acl = new Nette\Security\Permission;
$acl->addRole(/* ... */);
$acl->addResource(/* ... */);
$acl->allow(/* ... */);
return $acl;
}
}
```
And we will add it to the configuration:
```neon
services:
- App\Model\AuthorizatorFactory::create
```
In presenters, you can then verify permissions in the `startup()` method, for example:
```php
protected function startup()
{
parent::startup();
if (!$this->getUser()->isAllowed('backend')) {
$this->error('Forbidden', 403);
}
}
```