Skip to content

Commit fd0f21e

Browse files
Simperfitmeyerbaptiste
authored andcommitted
feature: add doc for access_control #230 (#231)
1 parent d7232c5 commit fd0f21e

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

core/security.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,58 @@ section.
66
Using API Platform, you can leverage all security features provided by the [Symfony Security component](http://symfony.com/doc/current/book/security.html).
77
For instance, if you wish to restrict the access of some endpoints, you can use [access controls directives](http://symfony.com/doc/current/book/security.html#securing-url-patterns-access-control).
88

9+
Since 2.1, you can add security through [Symfony's access control expressions](https://symfony.com/doc/current/expressions.html#security-complex-access-controls-with-expressions) in your entities.
10+
11+
Here is an example:
12+
13+
```php
14+
use ApiPlatform\Core\Annotation\ApiResource;
15+
use Doctrine\ORM\Mapping as ORM;
16+
use Symfony\Component\Validator\Constraints as Assert;
17+
18+
/**
19+
* Secured resource.
20+
*
21+
* @ApiResource(
22+
* attributes={"access_control"="is_granted('ROLE_USER')},
23+
* collectionOperations={
24+
* "get"={"method"="GET"},
25+
* "post"={"method"="POST", "access_control"="is_granted('ROLE_USER')}
26+
* },
27+
* itemOperations={
28+
* "get"={"method"="GET", "access_control"="is_granted('ROLE_USER') and object.owner == user"}
29+
* }
30+
* )
31+
* @ORM\Entity
32+
*/
33+
class Book
34+
{
35+
/**
36+
* @var int
37+
*
38+
* @ORM\Column(type="integer")
39+
* @ORM\Id
40+
* @ORM\GeneratedValue(strategy="AUTO")
41+
*/
42+
public $id;
43+
44+
/**
45+
* @var string The title
46+
*
47+
* @ORM\Column
48+
* @Assert\NotBlank
49+
*/
50+
public $title;
51+
52+
/**
53+
* @ORM\Column
54+
*/
55+
public $owner;
56+
}
57+
```
58+
59+
This exemple is going to allow only fetching the book related to the current user. if he tries to fetch a book that is linked to his account, that will not return the resource. In addition, only admins are able to create books which means that a user could not create a book.
60+
961
It is also possible to use the [event system](events.md) for more advanced logic or even [custom actions](operations.md#creating-custom-operations-and-controllers)
1062
if you really need to.
1163

0 commit comments

Comments
 (0)