diff --git a/core/security.md b/core/security.md index 5dadaeb716f..ed9eef1b7da 100644 --- a/core/security.md +++ b/core/security.md @@ -1,353 +1,12 @@ # Security -The API Platform security layer is built on top of the [Symfony Security component](https://symfony.com/doc/current/security.html). -All its features, including [global access control directives](https://symfony.com/doc/current/security.html#securing-url-patterns-access-control) are supported. -API Platform also provides convenient [access control expressions](https://symfony.com/doc/current/expressions.html#security-complex-access-controls-with-expressions) which you can apply at resource and operation level. +API Platform provides advanced authentication and authorization features to secure your API. -

Security screencast
Watch the Security screencast

+When using API Platform for Symfony, API Platform leverages the [Symfony Security component](https://symfony.com/doc/current/security.html) +to help you secure your API. - +When using API Platform for Laravel, it provides an integration with popular authentication packages for Laravel, and +with the built-in authorization features of the framework. -```php - - -Resource signature can be modified at the property level as well: - - - -```php - - -In this example: - -- The user must be logged in to interact with `Book` resources (configured at the resource level) -- Only users having [the role](https://symfony.com/doc/current/security.html#roles) `ROLE_ADMIN` can create a new resource (configured on the `post` operation) -- Only users having the `ROLE_ADMIN` or owning the current object can replace an existing book (configured on the `put` operation) -- Only users having the `ROLE_ADMIN` can view or modify the `adminOnlyProperty` property. Only users having the `ROLE_ADMIN` can create a new resource specifying `adminOnlyProperty` value. -- Only users that are granted the `UPDATE` attribute on the book (via a voter) can write to the field - -Available variables are: - -- `user`: the current logged in object, if any -- `object`: the current resource class during denormalization, the current resource during normalization, or collection of resources for collection operations -- `previous_object`: (`securityPostDenormalize` only) a clone of `object`, before modifications were made - this is `null` for create operations -- `request` (only at the resource level): the current request - -Access control checks in the `security` attribute are always executed before the [denormalization step](serialization.md). -It means that for `PUT` or `PATCH` requests, `object` doesn't contain the value submitted by the user, but values currently stored in [the persistence layer](state-processors.md). - -## Executing Access Control Rules After Denormalization - -In some cases, it might be useful to execute a security after the denormalization step. -To do so, use the `securityPostDenormalize` attribute: - - - -```php - - -This time, the `object` variable contains data that have been extracted from the HTTP request body during the denormalization process. -However, the object is not persisted yet. - -Additionally, in some cases you need to perform security checks on the original data. For example here, only the actual owner should be allowed to edit their book. In these cases, you can use the `previous_object` variable which contains the object that was read from the state provider. - -The value in the `previous_object` variable is cloned from the original object. -Note that, by default, this clone is not a deep one (it doesn't clone relationships, relationships are references). -To make a deep clone, [implement `__clone` method](https://www.php.net/manual/en/language.oop5.cloning.php) in the concerned resource class. - -## Hooking Custom Permission Checks Using Voters - -The easiest and recommended way to hook custom access control logic is [to write Symfony Voter classes](https://symfony.com/doc/current/security/voters.html). Your custom voters will automatically be used in security expressions through the `is_granted()` function. - -In order to give the current `object` to your voter, use the expression `is_granted('READ', object)` - -For example: - - - -```php - - -Please note that if you use both `security: "..."` and then `"post" => ["securityPostDenormalize" => "..."]`, the `security` on top level is called first, and after `securityPostDenormalize`. This could lead to unwanted behaviour, so avoid using both of them simultaneously. -If you need to use `securityPostDenormalize`, consider adding `security` for the other operations instead of the global one. - -Create a _BookVoter_ with the `bin/console make:voter` command: - -```php -security = $security; - } - - protected function supports($attribute, $subject): bool - { - $supportsAttribute = in_array($attribute, ['BOOK_CREATE', 'BOOK_READ', 'BOOK_EDIT', 'BOOK_DELETE']); - $supportsSubject = $subject instanceof Book; - - return $supportsAttribute && $supportsSubject; - } - - /** - * @param string $attribute - * @param Book $subject - * @param TokenInterface $token - * @return bool - */ - protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool - { - /** ... check if the user is anonymous ... **/ - - switch ($attribute) { - case 'BOOK_CREATE': - if ( $this->security->isGranted(Role::ADMIN) ) { return true; } // only admins can create books - break; - case 'BOOK_READ': - /** ... other authorization rules ... **/ - } - - return false; - } -} -``` - -_Note 1: When using Voters on POST methods: The voter needs an `$attribute` and `$subject` as input parameter, so you have to use the `securityPostDenormalize` (i.e. `"post" = { "securityPostDenormalize" = "is_granted('BOOK_CREATE', object)" }` ) because the object does not exist before denormalization (it is not created, yet.)_ - -_Note 2: You can't use Voters on the collection GET method, use [Collection Filters](https://api-platform.com/docs/core/security/#filtering-collection-according-to-the-current-user-permissions) instead._ - -## Configuring the Access Control Error Message - -By default when API requests are denied, you will get the "Access Denied" message. -You can change it by configuring the `securityMessage` attribute or the `securityPostDenormalizeMessage` attribute. - -For example: - - - -```php - - -## Filtering Collection According to the Current User Permissions - -Filtering collections according to the role or permissions of the current user must be done directly at [the state provider](state-providers.md) level. For instance, when using the built-in adapters for Doctrine ORM, MongoDB and ElasticSearch, removing entries from a collection should be done using [extensions](extensions.md). -Extensions allow to customize the generated DQL/Mongo/Elastic/... query used to retrieve the collection (e.g. add `WHERE` clauses depending of the currently connected user) instead of using access control expressions. -As extensions are services, you can [inject the Symfony `Security` class](https://symfony.com/doc/current/security.html#b-fetching-the-user-from-a-service) into them to access to current user's roles and permissions. - -If you use [custom state providers](state-providers.md), you'll have to implement the filtering logic according to the persistence layer you rely on. - -## Disabling Operations - -To completely disable some operations from your application, refer to the [disabling operations](operations.md#enabling-and-disabling-operations) -section. - -## Changing Serialization Groups Depending of the Current User - -See [how to dynamically change](serialization.md#changing-the-serialization-context-dynamically) the current Serializer context according to the current logged in user. +- For Symfony users, refer to the [Security with Symfony documentation](/symfony/security.md). +- For Laravel users, refer to the [Security with Laravel documentation](/laravel/security.md). diff --git a/laravel/security.md b/laravel/security.md index 0d0b2751730..c501d026ab3 100644 --- a/laravel/security.md +++ b/laravel/security.md @@ -1,8 +1,13 @@ -# Security +# Security with Laravel ## Policies -API platform is compatible with Laravel [authorization](https://laravel.com/docs/authorization) mechanism. Once a gate is defined, API Platform will automatically detect your policy. +API Platform is compatible with Laravel's [authorization](https://laravel.com/docs/authorization) mechanism. + +To utilize policies in API Platform, it is essential to have Laravel's authentication system initialized. +See the [Authentification section](#authentication) for more information. + +Once a gate is defined, API Platform will automatically detect your policy. ```php // app/Models/Book.php @@ -15,7 +20,8 @@ class Book extends Model } ``` -API Platform will detect the operation and map it to a specific method in your policy according to the rules defined in this table: +API Platform will detect the operation and map it to a specific method in your policy according to the rules defined in +this table: | Operation | Policy | | -------------- | ---------------------------------------------------------- | @@ -26,7 +32,8 @@ API Platform will detect the operation and map it to a specific method in your p | DELETE | `delete` | | PUT | `update` or `create` if the resource doesn't already exist | -If your policy methods do not match Laravel's conventions, you can always use the `policy` property on an operation attribute to enforce this policy: +If your policy methods do not match Laravel's conventions, you can always use the `policy` property on an operation +attribute to enforce this policy: ```php // app/Models/Book.php @@ -78,3 +85,17 @@ class Book extends Model { } ``` + +Or you can define it globally in the configuration by adding the following code: + +```php + [ + // .... + 'middleware' => 'auth:sanctum', + ], +]; +``` diff --git a/outline.yaml b/outline.yaml index 8b892d2ecd1..aff18ecd8d0 100644 --- a/outline.yaml +++ b/outline.yaml @@ -4,6 +4,7 @@ chapters: path: symfony items: - index + - security - testing - debugging - caddy diff --git a/symfony/security.md b/symfony/security.md new file mode 100644 index 00000000000..a8848cdff9d --- /dev/null +++ b/symfony/security.md @@ -0,0 +1,353 @@ +# Security with Symfony + +The API Platform security layer is built on top of the [Symfony Security component](https://symfony.com/doc/current/security.html). +All its features, including [global access control directives](https://symfony.com/doc/current/security.html#securing-url-patterns-access-control) are supported. +API Platform also provides convenient [access control expressions](https://symfony.com/doc/current/expressions.html#security-complex-access-controls-with-expressions) which you can apply at resource and operation level. + +

Security screencast
Watch the Security screencast

+ + + +```php + + +Resource signature can be modified at the property level as well: + + + +```php + + +In this example: + +- The user must be logged in to interact with `Book` resources (configured at the resource level) +- Only users having [the role](https://symfony.com/doc/current/security.html#roles) `ROLE_ADMIN` can create a new resource (configured on the `post` operation) +- Only users having the `ROLE_ADMIN` or owning the current object can replace an existing book (configured on the `put` operation) +- Only users having the `ROLE_ADMIN` can view or modify the `adminOnlyProperty` property. Only users having the `ROLE_ADMIN` can create a new resource specifying `adminOnlyProperty` value. +- Only users that are granted the `UPDATE` attribute on the book (via a voter) can write to the field + +Available variables are: + +- `user`: the current logged in object, if any +- `object`: the current resource class during denormalization, the current resource during normalization, or collection of resources for collection operations +- `previous_object`: (`securityPostDenormalize` only) a clone of `object`, before modifications were made - this is `null` for create operations +- `request` (only at the resource level): the current request + +Access control checks in the `security` attribute are always executed before the [denormalization step](serialization.md). +It means that for `PUT` or `PATCH` requests, `object` doesn't contain the value submitted by the user, but values currently stored in [the persistence layer](state-processors.md). + +## Executing Access Control Rules After Denormalization + +In some cases, it might be useful to execute a security after the denormalization step. +To do so, use the `securityPostDenormalize` attribute: + + + +```php + + +This time, the `object` variable contains data that have been extracted from the HTTP request body during the denormalization process. +However, the object is not persisted yet. + +Additionally, in some cases you need to perform security checks on the original data. For example here, only the actual owner should be allowed to edit their book. In these cases, you can use the `previous_object` variable which contains the object that was read from the state provider. + +The value in the `previous_object` variable is cloned from the original object. +Note that, by default, this clone is not a deep one (it doesn't clone relationships, relationships are references). +To make a deep clone, [implement `__clone` method](https://www.php.net/manual/en/language.oop5.cloning.php) in the concerned resource class. + +## Hooking Custom Permission Checks Using Voters + +The easiest and recommended way to hook custom access control logic is [to write Symfony Voter classes](https://symfony.com/doc/current/security/voters.html). Your custom voters will automatically be used in security expressions through the `is_granted()` function. + +In order to give the current `object` to your voter, use the expression `is_granted('READ', object)` + +For example: + + + +```php + + +Please note that if you use both `security: "..."` and then `"post" => ["securityPostDenormalize" => "..."]`, the `security` on top level is called first, and after `securityPostDenormalize`. This could lead to unwanted behaviour, so avoid using both of them simultaneously. +If you need to use `securityPostDenormalize`, consider adding `security` for the other operations instead of the global one. + +Create a _BookVoter_ with the `bin/console make:voter` command: + +```php +security = $security; + } + + protected function supports($attribute, $subject): bool + { + $supportsAttribute = in_array($attribute, ['BOOK_CREATE', 'BOOK_READ', 'BOOK_EDIT', 'BOOK_DELETE']); + $supportsSubject = $subject instanceof Book; + + return $supportsAttribute && $supportsSubject; + } + + /** + * @param string $attribute + * @param Book $subject + * @param TokenInterface $token + * @return bool + */ + protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool + { + /** ... check if the user is anonymous ... **/ + + switch ($attribute) { + case 'BOOK_CREATE': + if ( $this->security->isGranted(Role::ADMIN) ) { return true; } // only admins can create books + break; + case 'BOOK_READ': + /** ... other authorization rules ... **/ + } + + return false; + } +} +``` + +_Note 1: When using Voters on POST methods: The voter needs an `$attribute` and `$subject` as input parameter, so you have to use the `securityPostDenormalize` (i.e. `"post" = { "securityPostDenormalize" = "is_granted('BOOK_CREATE', object)" }` ) because the object does not exist before denormalization (it is not created, yet.)_ + +_Note 2: You can't use Voters on the collection GET method, use [Collection Filters](https://api-platform.com/docs/core/security/#filtering-collection-according-to-the-current-user-permissions) instead._ + +## Configuring the Access Control Error Message + +By default when API requests are denied, you will get the "Access Denied" message. +You can change it by configuring the `securityMessage` attribute or the `securityPostDenormalizeMessage` attribute. + +For example: + + + +```php + + +## Filtering Collection According to the Current User Permissions + +Filtering collections according to the role or permissions of the current user must be done directly at [the state provider](state-providers.md) level. For instance, when using the built-in adapters for Doctrine ORM, MongoDB and ElasticSearch, removing entries from a collection should be done using [extensions](extensions.md). +Extensions allow to customize the generated DQL/Mongo/Elastic/... query used to retrieve the collection (e.g. add `WHERE` clauses depending of the currently connected user) instead of using access control expressions. +As extensions are services, you can [inject the Symfony `Security` class](https://symfony.com/doc/current/security.html#b-fetching-the-user-from-a-service) into them to access to current user's roles and permissions. + +If you use [custom state providers](state-providers.md), you'll have to implement the filtering logic according to the persistence layer you rely on. + +## Disabling Operations + +To completely disable some operations from your application, refer to the [disabling operations](operations.md#enabling-and-disabling-operations) +section. + +## Changing Serialization Groups Depending of the Current User + +See [how to dynamically change](serialization.md#changing-the-serialization-context-dynamically) the current Serializer context according to the current logged in user.