Access Control (Authorization)
May the user enter the administration? Edit this article? Delete someone else's comment? These are the questions authorization
answers, and in Nette each of them takes a single call to $user->isAllowed():
- you write the rules in small classes, each next to the part of the application it concerns
- you decide about concrete objects, not just roles: an article may be edited by its author
- a logged-out user or a visitor never gets someone else's rights, even if you forget to think about it in your code
→ Installation and requirements
In the examples, we will use an object of the class Nette\Security\User, which represents the current user
and which you get by having it passed to you using dependency injection. In presenters, just call
$user = $this->getUser().
For very simple websites with administration where user permissions are not differentiated, the already known method
isLoggedIn() can be used as the authorization criterion. In other words: as soon as a user is logged in, they have
all permissions, and vice versa.
if ($user->isLoggedIn()) { // is the user logged in?
deleteItem(); // then they have permission for the operation
}
For such a site, this is a perfectly legitimate criterion. The voters that most of this page is about start paying off once a
second kind of user, roles, or the question of who owns what come into play. If you want to ask through isAllowed()
from the start anyway, a single-line voter will do.
Roles
The purpose of roles is to offer more precise control over permissions and remain independent of the username. As soon as a
user logs in, they are assigned one or more roles in which they will act. Roles are simple names, for example, admin,
member, guest, etc. They are specified as the second argument of the SimpleIdentity
constructor, either as a string or an array of strings.
As an authorization criterion, we will now use the isInRole() method, which reveals whether the user is acting in
the given role:
if ($user->isInRole('admin')) { // is the user in the admin role?
deleteItem(); // then they have permission for the operation
}
As you already know, logging out the user does not have to delete their identity. Thus, the getIdentity() method
still returns the identity, including all granted roles. Nette Framework espouses the principle “less code, more security,”
where less writing leads to more secure code. Therefore, when checking roles, you do not need to verify whether the user is logged
in. The isInRole() method works with effective roles: if the user is logged in, it is based on the roles
specified in the identity; if not logged in, they automatically have the special role guest (or the roles of the guest identity, if one is provided).
May This User Edit This Article?
Roles tell you who the user is, but often that is not enough. Imagine a blog where every registered user can write articles, but may edit only their own. Here the role does not decide, the particular article does: who its author is.
In our examples, an article will be a plain object carrying its ID, the ID of its author, and whether it is published and whether it is locked:
class Article
{
public function __construct(
public int $id,
public int $authorId,
public bool $published = false,
public bool $locked = false,
) {
}
}
We write the rules for articles in a separate class called a voter. It is a small object that decides about one kind of
thing, in our case about articles. It implements the Nette\Security\Voter interface with a single method
vote():
namespace App\Model;
use Nette\Security\{Principal, Vote, Voter};
class ArticleVoter implements Voter
{
public function vote(Principal $principal, mixed $resource, ?string $privilege): Vote
{
if (!$resource instanceof Article) {
return Vote::Abstain; // not an article, not my business
}
return Vote::allowIf(match ($privilege) {
'view' => $resource->published || $principal->hasId($resource->authorId),
'edit', 'delete' => $principal->hasId($resource->authorId),
default => false,
});
}
}
The vote() method receives three things. $principal is the user the decision is about (why it is not
$user itself, we will explain in a moment).
$resource is the resource, what they want to access, in our case the article. And $privilege is
the privilege, the operation they want to perform on it, such as view, edit or
delete. A resource does not have to be an object; it can also be a plain name or a class name, and we will get
to both.
The answer is a vote, one of the values of the Vote enum. The Vote::allowIf() method turns a
condition into either Vote::Allow (I allow it) or Vote::Abstain (I abstain, let others decide).
The hasId() method checks that the user is logged in and has the given ID. So a published article can be viewed by
anyone, a draft only by its author, and only the author may edit or delete an article. For any other operation, the
default => false branch makes the voter allow nothing and abstain.
How much configuration does it take for Nette to start asking the voter? You just register it as a service. Nette recognizes that it implements the
Voter interface, and you don't have to set up anything else:
services:
- App\Model\ArticleVoter
If you register services automatically using the search section, you don't even need that.
Do you use the User class without the DI container? Then pass the voter to its constructor after the storage and the authenticator, or add it with the
addVoter() method:
$user = new Nette\Security\User($storage, $authenticator, new ArticleVoter);
// or
$user = new Nette\Security\User($storage, $authenticator);
$user->addVoter(new ArticleVoter);
If $user has no voter at all, the isAllowed() method throws Nette\InvalidStateException
instead of quietly denying everything.
Other slips are not so loud. A typo in the name of a resource or privilege, or a voter you forgot to register (while you have
others), simply ends in false. So keep names you use in many places in constants or in a class, rather than typing
the string again each time.
And now the check itself. In a presenter, you ask the $user object, not the voter:
public function actionEdit(int $id): void
{
$article = $this->articleRepository->getById($id); // loads the article from the database
if (!$this->getUser()->isAllowed($article, 'edit')) {
$this->error('You cannot edit this article.', 403);
}
// here goes the preparation of the form for editing the article
}
The same goes for a template, where the $user variable is always available. Only those who may edit the article
will see the link to edit it:
<a n:if="$user->isAllowed($article, 'edit')" n:href="edit, $article->id">Edit</a>
Notice that the code checking the permission has no idea who decides about it and how. The rules for articles live in one
place, in ArticleVoter.
How Voters Reach a Decision
An application usually has several voters, each for its own area: one for articles, others for comments, orders or photos. Nette asks all of them every question. A voter the question does not concern abstains, and the voter in charge of that kind of thing decides.
Let's add an administrator who may do everything:
class AdminVoter implements Voter
{
public function vote(Principal $principal, mixed $resource, ?string $privilege): Vote
{
return Vote::allowIf($principal->isInRole('admin'));
}
}
You register it as a service just like ArticleVoter. Without it, we would have to add the condition
isInRole('admin') to every voter. This way ArticleVoter still allows only the author,
AdminVoter allows the admin, and since one approval is enough, the admin may edit any article.
Sometimes, however, you need the opposite: a rule that nobody can override. For example, a locked article may not be edited by
its author or by the admin. That is what the third vote, Vote::Forbid, is for. We add it to ArticleVoter
right after the instanceof check:
if ($resource->locked && $privilege === 'edit') {
return Vote::Forbid; // nobody edits a locked article, not even an admin
}
So the result is put together by a simple rule:
- when any voter says
Forbid, it is forbidden, no matter what the others say - otherwise, it is enough for one voter to say
Allow - when all of them abstain (
Abstain), it is forbidden
The order of voters does not matter. And forbidding is only ever deliberate: an ordinary voter returns
Vote::allowIf(), so a plain condition can never turn into a prohibition. That is why ArticleVoter, which
allows only the author, does not lock out the admin.
The admin may still delete a locked article, because Forbid applies only to the operation you wrote it for.
Be careful with AdminVoter, though. Nette asks every voter about every resource and every privilege, so an
unconditional allow really allows everything: the sections of another kind of user, such as a customer's account, as well as
operations nobody should perform, such as deleting one's own account. So narrow it down to the resources the admin is meant for,
or let the voters in charge of such things say Forbid.
Does your site have just a single account for the administration, defined in the configuration under security: users:? Then the voter is
even simpler than AdminVoter, because whoever is logged in is the admin:
return Vote::allowIf($principal->isLoggedIn());
Why not by role? A user defined in users: without roles has an empty list of roles, the role
authenticated known from older versions no longer exists, and a negated isInRole('guest') only tells you
that the user lacks one particular role, not that they are logged in.
A banned user who may not do anything at all can be handled in authentication: when the
wakeupIdentity() method returns null, Nette logs them out and to the voters they are an ordinary
visitor. That, however, applies only to their own visit to the site. If the ban should also hold when deciding for someone else, write a voter that returns Vote::Forbid for a
banned user.
Principal: Who the Decision Is About
You may be wondering why a voter does not get the $user object directly. There is a good reason for it, and it has
to do with security.
As you already know, logging out does not have to
delete the user's identity. That is why $user->getId() returns their ID even after they have logged out or
their login has expired. If a voter got $user and compared the author of an article with its getId(), a
logged-out user could keep editing their articles. And a visitor could edit an article that has no author at all, because both
values would be null.
So a voter gets a Principal, which is the user as authorization sees them. It has an identity only when the user
is really logged in, and it offers exactly what a voter needs:
hasId($id)checks that this is the logged-in user with the given ID; for a visitor it always returnsfalseisLoggedIn()tells whether this is a logged-in user, that is, whether the principal has an identityisInRole($role)andgetRoles()work with the effective roles, just like on$usergetIdentity()returns the identity of the logged-in user including their data,nullfor a visitor, even when$userkeeps a retained identity or a guest identitygetGuestIdentity()returns the guest identity for a visitor andnullfor a logged-in user; a voter that needs the data of either one writes$principal->getIdentity() ?? $principal->getGuestIdentity()isAllowed($resource, $privilege)asks all the voters, which we will get to in the next chapter
The principal deliberately has no getId() method. You check ownership with hasId(), so you cannot
make either of the mistakes above, even if you forget to think about them. Less code, more security.
Keep in mind that hasId() compares only the ID. When one User serves two kinds of users whose IDs
come from separate tables and may overlap, such as customers and employees, combine ownership with the role:
$principal->isInRole('customer') && $principal->hasId($order->customerId).
The principal of the current user is returned at any time by the $user->getPrincipal() method.
The hasId() method compares strictly, so the ID must have the same type. SimpleIdentity
converts numeric IDs to int, so it matches IDs from the database; if you have your own identity with a string ID,
compare with the same type.
A Voter Can Ask Another One
Comments have their own rules: a comment may be viewed by anyone who may view the article it belongs to, and only its author may edit it. A comment will again be a plain object:
class Comment
{
public function __construct(
public Article $article,
public int $authorId,
) {
}
}
We already have the rules for viewing articles in ArticleVoter and don't want to copy them. So
CommentVoter asks the principal, just as you ask the $user object:
class CommentVoter implements Voter
{
public function vote(Principal $principal, mixed $resource, ?string $privilege): Vote
{
if (!$resource instanceof Comment) {
return Vote::Abstain;
}
return Vote::allowIf(match ($privilege) {
'view' => $principal->isAllowed($resource->article, 'view'),
'edit' => $principal->hasId($resource->authorId),
default => false,
});
}
}
The principal asks all the voters, so both ArticleVoter and AdminVoter decide whether the article is
visible, exactly as if the user were asking directly. Register this voter as a service too, and you are done.
Permissions Without a Particular Object
May the user write a new article? Here we are asking about something that does not exist yet, so instead of an article we ask about its class:
if ($user->isAllowed(Article::class, 'create')) {
// shows the link for writing a new article
}
In ArticleVoter, a single condition at the beginning of the vote() method is enough, before the
instanceof check. The whole voter now looks like this:
class ArticleVoter implements Voter
{
public function vote(Principal $principal, mixed $resource, ?string $privilege): Vote
{
if ($resource === Article::class) { // a question about articles in general
return Vote::allowIf($privilege === 'create' && $principal->isInRole('registered'));
}
if (!$resource instanceof Article) {
return Vote::Abstain; // not an article, not my business
}
if ($resource->locked && $privilege === 'edit') {
return Vote::Forbid; // nobody edits a locked article, not even an admin
}
return Vote::allowIf(match ($privilege) {
'view' => $resource->published || $principal->hasId($resource->authorId),
'edit', 'delete' => $principal->hasId($resource->authorId),
default => false,
});
}
}
Deciding for Someone Else
Sometimes you need to ask about the permissions of a user other than the one currently browsing the site. For example, when
sending notifications about a new article that should go only to those who may read it. That is what the
createPrincipal() method is for, which you call in any service that has Nette\Security\User passed
to it:
foreach ($this->subscriberRepository->getIdentities() as $identity) { // identities of all subscribers
if ($this->user->createPrincipal($identity)->isAllowed($article, 'view')) {
// sends the subscriber an e-mail about the new article
}
}
The principal asks the same voters as $user, but it does not affect the login of the current user in any way. It
takes the identity exactly as you pass it: it does not call the authenticator's wakeupIdentity() method for it and
stores nothing. So load it from the database in its current form, with the current roles.
Instead of an identity, you can pass null and ask what an anonymous visitor may do. This comes in handy, for
example, when generating an RSS feed or a sitemap, which should contain only the articles everyone can see:
$visitor = $this->user->createPrincipal(null);
if ($visitor->isAllowed($article, 'view')) {
// adds the article to the RSS feed
}
A voter decides about one object at a time, and these examples ask about a single article. When you go through large sets, such as listings, feeds, sitemaps or notifications to thousands of users, asking about every row is slow. Filter right in the database query instead, for example by selecting only published articles, and make sure the condition in the query agrees with what the voter says.
Testing Voters
A voter is a plain class that needs neither a session nor a login, which makes it easy to test. You create the principal
yourself: the first argument is the identity of the logged-in user (or null for a visitor), the second their roles.
The example uses Nette Tester:
use Nette\Security\{Principal, SimpleIdentity, Vote};
use Tester\Assert;
$voter = new ArticleVoter;
$draft = new Article(id: 1, authorId: 1);
$author = new Principal(new SimpleIdentity(1), ['registered']);
Assert::same(Vote::Allow, $voter->vote($author, $draft, 'edit'));
$guest = new Principal(null, ['guest']);
Assert::same(Vote::Abstain, $voter->vote($guest, $draft, 'edit'));
If you want to test how voters work together, pass them to the principal as the third argument and ask its
isAllowed() method:
$guest = new Principal(null, ['guest'], [new ArticleVoter, new CommentVoter]);
Assert::false($guest->isAllowed(new Comment($draft, authorId: 2), 'view'));
Rules for Roles and Sections of the Site
Not every permission concerns an object. For example, only editors may enter the administration, whichever of its pages it is. Rules like these between roles and sections of the site are conveniently written in the ACL that comes with Nette. Just list them in the configuration:
security:
roles:
guest:
registered: [guest]
editor: [registered]
admin: [registered]
resources:
backend:
rules:
allow:
- [editor, backend]
To Nette, the ACL is just another voter, so you ask in exactly the same way. This time the resource is the name of the section, and we leave out the privilege, because we are interested in the section as a whole:
if (!$this->getUser()->isAllowed('backend')) {
$this->error('Forbidden', 403);
}
Leaving out the privilege means passing null. To your own voter, that simply says no particular privilege was
asked; it is the ACL that reads null as all privileges (and a left-out resource as all resources).
Voters and the ACL complement each other: the ACL decides by roles and section names, voters about particular objects. You can read how the ACL works and everything it can do in the chapter ACL.
Your own authorizator implementing Nette\Security\Authorizator that decides by roles still works, but
it is deprecated, so rewrite it as a voter, as shown in upgrading to version 4.0.