Skip to content

[GraphQL] Security #471

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 1, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 44 additions & 1 deletion core/graphql.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ Filters are supported out-of-the-box. Follow the [filters](filters.md) documenta
However you don't necessarily have the same needs for your GraphQL endpoint as for your REST one.

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

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

Expand All @@ -59,7 +60,10 @@ use ApiPlatform\Core\Annotation\ApiResource;
* graphql={
* "query"={
* "filters"={"offer.date_filter"}
* }
* },
* "delete",
* "update",
* "create"
* }
* )
*/
Expand Down Expand Up @@ -131,3 +135,42 @@ Or order your results like:
}
}
```

## Security (`access_control`)

To add a security layer to your queries and mutations, follow the [security](security.md) documentation.

If your security needs differ between REST and GraphQL, add the particular parts in the `graphql` key.

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.
Please note it's not possible to update a book in GraphQL because the `update` operation is not defined.

```php
<?php
// api/src/Entity/Book.php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;

/**
* @ApiResource(
* attributes={"access_control"="is_granted('ROLE_USER')"},
* collectionOperations={
* "post"={"access_control"="is_granted('ROLE_ADMIN')", "access_control_message"="Only admins can add books."}
* },
* itemOperations={
* "get"={"access_control"="is_granted('ROLE_USER') and object.owner == user", "access_control_message"="Sorry, but you are not the book owner."}
* },
* graphql={
* "query"={"access_control"="is_granted('ROLE_USER') and object.owner == user"},
* "delete"={"access_control"="is_granted('ROLE_ADMIN')"},
* "create"={"access_control"="is_granted('ROLE_ADMIN')"}
* }
* )
*/
class Book
{
// ...
}
```