Skip to content

Commit 89138fe

Browse files
authored
Merge pull request #471 from alanpoulain/graphql-security
[GraphQL] Security
2 parents e674472 + 61f4461 commit 89138fe

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

core/graphql.md

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ Filters are supported out-of-the-box. Follow the [filters](filters.md) documenta
4040
However you don't necessarily have the same needs for your GraphQL endpoint as for your REST one.
4141

4242
In the `ApiResource` declaration, you can choose to decorrelate the GraphQL filters in `query` of the `graphql` attribute.
43+
In order to keep the default behavior (possibility to fetch, delete, update or create), define all the operations (`query`, `delete`, `update` and `create`).
4344

4445
For example, this entity will have a search filter for REST and a date filter for GraphQL:
4546

@@ -59,7 +60,10 @@ use ApiPlatform\Core\Annotation\ApiResource;
5960
* graphql={
6061
* "query"={
6162
* "filters"={"offer.date_filter"}
62-
* }
63+
* },
64+
* "delete",
65+
* "update",
66+
* "create"
6367
* }
6468
* )
6569
*/
@@ -131,3 +135,42 @@ Or order your results like:
131135
}
132136
}
133137
```
138+
139+
## Security (`access_control`)
140+
141+
To add a security layer to your queries and mutations, follow the [security](security.md) documentation.
142+
143+
If your security needs differ between REST and GraphQL, add the particular parts in the `graphql` key.
144+
145+
In the example below, we want the same security rules as in REST, but we also want to allow an admin to delete a book in GraphQL only.
146+
Please note it's not possible to update a book in GraphQL because the `update` operation is not defined.
147+
148+
```php
149+
<?php
150+
// api/src/Entity/Book.php
151+
152+
namespace App\Entity;
153+
154+
use ApiPlatform\Core\Annotation\ApiResource;
155+
156+
/**
157+
* @ApiResource(
158+
* attributes={"access_control"="is_granted('ROLE_USER')"},
159+
* collectionOperations={
160+
* "post"={"access_control"="is_granted('ROLE_ADMIN')", "access_control_message"="Only admins can add books."}
161+
* },
162+
* itemOperations={
163+
* "get"={"access_control"="is_granted('ROLE_USER') and object.owner == user", "access_control_message"="Sorry, but you are not the book owner."}
164+
* },
165+
* graphql={
166+
* "query"={"access_control"="is_granted('ROLE_USER') and object.owner == user"},
167+
* "delete"={"access_control"="is_granted('ROLE_ADMIN')"},
168+
* "create"={"access_control"="is_granted('ROLE_ADMIN')"}
169+
* }
170+
* )
171+
*/
172+
class Book
173+
{
174+
// ...
175+
}
176+
```

0 commit comments

Comments
 (0)