security.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. Security
  2. ========
  3. The security part is managed by a ``SecurityHandler``, the bundle comes with 3 handlers
  4. - ``sonata.admin.security.handler.role`` : ROLES to handle permissions
  5. - ``sonata.admin.security.handler.acl`` : ACL and ROLES to handle permissions
  6. - ``sonata.admin.security.handler.noop`` : always return true, can be used with the Symfony2 firewall
  7. The default value is ``sonata.admin.security.handler.noop``, if you want to change the default value
  8. you can set the ``security_handler`` to ``sonata.admin.security.handler.acl`` or ``sonata.admin.security.handler.role``.
  9. To quickly secure an admin the role security can be used. It allows to specify the actions a user can with the admin. The ACL
  10. security system is more advanced and allows to secure the objects. For people using the previous ACL implementation,
  11. you can switch the security_handler to the role security handler.
  12. Configuration
  13. ~~~~~~~~~~~~~
  14. Only the security handler is required to determine which type of security to use. The other parameters are set as default,
  15. change them if needed.
  16. Using roles:
  17. .. code-block:: yaml
  18. sonata_admin:
  19. security:
  20. handler: sonata.admin.security.handler.role
  21. # role security information
  22. information:
  23. EDIT: EDIT
  24. LIST: LIST
  25. CREATE: CREATE
  26. VIEW: VIEW
  27. DELETE: DELETE
  28. OPERATOR: OPERATOR
  29. MASTER: MASTER
  30. Using ACL:
  31. .. code-block:: yaml
  32. sonata_admin:
  33. security:
  34. handler: sonata.admin.security.handler.acl
  35. # acl security information
  36. information:
  37. GUEST: [VIEW, LIST]
  38. STAFF: [EDIT, LIST, CREATE]
  39. EDITOR: [OPERATOR]
  40. ADMIN: [MASTER]
  41. # permissions not related to an object instance and also to be available when objects do not exist
  42. # the DELETE admin permission means the user is allowed to batch delete objects
  43. admin_permissions: [CREATE, LIST, DELETE, UNDELETE, OPERATOR, MASTER]
  44. # permission related to the objects
  45. object_permissions: [VIEW, EDIT, DELETE, UNDELETE, OPERATOR, MASTER, OWNER]
  46. The following section explains how to set up ACL with the ``FriendsOfSymfony/UserBundle``.
  47. ACL and FriendsOfSymfony/UserBundle
  48. -----------------------------------
  49. If you want an easy way to handle users, please use :
  50. - https://github.com/FriendsOfSymfony/FOSUserBundle : handle users and group stored from RDMS or MongoDB
  51. - https://github.com/sonata-project/SonataUserBundle : integrate the ``FriendsOfSymfony/UserBundle`` with
  52. the ``AdminBundle``
  53. The security integration is a work in progress and have some knows issues :
  54. - ACL permissions are immutables
  55. - A listener must be implemented that creates the object Access Control List with the required rules if objects are
  56. created outside the Admin
  57. Configuration
  58. ~~~~~~~~~~~~~
  59. - The following configuration defines :
  60. - the ``FriendsOfSymfony/FOSUserBundle`` as a security provider
  61. - the login form for authentification
  62. - the access control : resources with related required roles, the important part is the admin configuration
  63. - the ``acl`` option enable the ACL.
  64. - the ``AdminPermissionMap`` defines the permissions of the Admin class
  65. .. code-block:: yaml
  66. # app/config/security.yml
  67. parameters:
  68. # ... other parameters
  69. security.acl.permission.map.class: Sonata\AdminBundle\Security\Acl\Permission\AdminPermissionMap
  70. # optionally use a custom MaskBuilder
  71. #sonata.admin.security.mask.builder.class: Sonata\AdminBundle\Security\Acl\Permission\MaskBuilder
  72. security:
  73. providers:
  74. fos_userbundle:
  75. id: fos_user.user_manager
  76. firewalls:
  77. main:
  78. pattern: .*
  79. form-login:
  80. provider: fos_userbundle
  81. login_path: /login
  82. use_forward: false
  83. check_path: /login_check
  84. failure_path: null
  85. logout: true
  86. anonymous: true
  87. access_control:
  88. # The WDT has to be allowed to anonymous users to avoid requiring the login with the AJAX request
  89. - { path: ^/wdt/, role: IS_AUTHENTICATED_ANONYMOUSLY }
  90. - { path: ^/profiler/, role: IS_AUTHENTICATED_ANONYMOUSLY }
  91. # AsseticBundle paths used when using the controller for assets
  92. - { path: ^/js/, role: IS_AUTHENTICATED_ANONYMOUSLY }
  93. - { path: ^/css/, role: IS_AUTHENTICATED_ANONYMOUSLY }
  94. # URL of FOSUserBundle which need to be available to anonymous users
  95. - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
  96. - { path: ^/login_check$, role: IS_AUTHENTICATED_ANONYMOUSLY } # for the case of a failed login
  97. - { path: ^/user/new$, role: IS_AUTHENTICATED_ANONYMOUSLY }
  98. - { path: ^/user/check-confirmation-email$, role: IS_AUTHENTICATED_ANONYMOUSLY }
  99. - { path: ^/user/confirm/, role: IS_AUTHENTICATED_ANONYMOUSLY }
  100. - { path: ^/user/confirmed$, role: IS_AUTHENTICATED_ANONYMOUSLY }
  101. - { path: ^/user/request-reset-password$, role: IS_AUTHENTICATED_ANONYMOUSLY }
  102. - { path: ^/user/send-resetting-email$, role: IS_AUTHENTICATED_ANONYMOUSLY }
  103. - { path: ^/user/check-resetting-email$, role: IS_AUTHENTICATED_ANONYMOUSLY }
  104. - { path: ^/user/reset-password/, role: IS_AUTHENTICATED_ANONYMOUSLY }
  105. # Secured part of the site
  106. # This config requires being logged for the whole site and having the admin role for the admin part.
  107. # Change these rules to adapt them to your needs
  108. - { path: ^/admin/, role: ROLE_ADMIN }
  109. - { path: ^/.*, role: IS_AUTHENTICATED_ANONYMOUSLY }
  110. role_hierarchy:
  111. ROLE_ADMIN: [ROLE_USER, ROLE_SONATA_ADMIN]
  112. ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
  113. acl:
  114. connection: default
  115. - Install the ACL tables ``php app/console init:acl``
  116. - Create a new user :
  117. .. code-block:: sh
  118. # php app/console fos:user:create
  119. Please choose a username:root
  120. Please choose an email:root@domain.com
  121. Please choose a password:root
  122. Created user root
  123. - Promote an user as super admin :
  124. .. code-block:: sh
  125. # php app/console fos:user:promote root
  126. User "root" has been promoted as a super administrator.
  127. If you have Admin classes, you can install or update the related CRUD ACL rules :
  128. .. code-block:: sh
  129. # php app/console sonata:admin:setup-acl
  130. Starting ACL AdminBundle configuration
  131. > install ACL for sonata.media.admin.media
  132. - add role: ROLE_SONATA_MEDIA_ADMIN_MEDIA_GUEST, permissions: ["VIEW","LIST"]
  133. - add role: ROLE_SONATA_MEDIA_ADMIN_MEDIA_STAFF, permissions: ["EDIT","LIST","CREATE"]
  134. - add role: ROLE_SONATA_MEDIA_ADMIN_MEDIA_EDITOR, permissions: ["OPERATOR"]
  135. - add role: ROLE_SONATA_MEDIA_ADMIN_MEDIA_ADMIN, permissions: ["MASTER"]
  136. ... skipped ...
  137. If you try to access to the admin class you should see the login form, just logon with the ``root`` user.
  138. An Admin is displayed in the dashboard (and menu) when the user has the role ``LIST``. To change this override the ``showIn``
  139. method in the Admin class.
  140. Roles and Access control lists
  141. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  142. A user can have several roles when working with an application. Each Admin class has several roles, and each role specifies the permissions
  143. of the user for the Admin class. Or more specific, what the user can do with the domain object(s) the Admin class is created for.
  144. By default each Admin class contains the following roles, override the property ``$securityInformation`` to change this:
  145. - ROLE_SONATA_..._GUEST: a guest that is allowed to view an object and a list of objects;
  146. - ROLE_SONATA_..._STAFF: probably the biggest part of the users, a staff user has the same permissions as guests and is additionally
  147. allowed to EDIT and CREATE new objects;
  148. - ROLE_SONATA_..._EDITOR: an editor is granted all access and, compared to the staff users, is allowed to DELETE;
  149. - ROLE_SONATA_..._ADMIN: an administrative user is granted all access and on top of that, the user is allowed to grant other users access.
  150. Owner:
  151. - when an object is created, the currently logged in user is set as owner for that object and is granted all access for that object;
  152. - this means the user owning the object is always allowed to DELETE the object, even when it only has the staff role.
  153. Vocabulary used for Access Control Lists:
  154. - Role: a user role;
  155. - ACL: a list of access rules, the Admin uses 2 types:
  156. - Admin ACL: created from the Security information of the Admin class for each admin and shares the Access Control Entries that specify
  157. what the user can do (permissions) with the admin
  158. - Object ACL: also created from the security information of the Admin class however created for each object, it uses 2 scopes:
  159. - Class-Scope: the class scope contains the rules that are valid for all object of a certain class;
  160. - Object-Scope: specifies the owner;
  161. - Sid: Security identity, an ACL role for the Class-Scope ACL and the user for the Object-Scope ACL;
  162. - Oid: Object identity, identifies the ACL, for the admin ACL this is the admin code, for the object ACL this is the object id;
  163. - ACE: a role (or sid) and its permissions;
  164. - Permission: this tells what the user is allowed to do with the Object identity;
  165. - Bitmask: a permission can have several bitmasks, each bitmask represents a permission. When permission VIEW is requested and
  166. it contains the VIEW and EDIT bitmask and the user only has the EDIT permission, then the permission VIEW is granted.
  167. - PermissionMap: configures the bitmasks for each permission, to change the default mapping create a voter for the domain class of the Admin.
  168. There can be many voters that may have different permission maps. However, prevent that multiple voters vote on the same class with
  169. overlapping bitmasks.
  170. See the cookbook article "Advanced ACL concepts" for the meaning of the different permissions:
  171. http://symfony.com/doc/current/cookbook/security/acl_advanced.html#pre-authorization-decisions.
  172. How is access granted?
  173. ~~~~~~~~~~~~~~~~~~~~~~
  174. In the application the security context is asked if access is granted for a role or a permission (admin.isGranted):
  175. - Token: a token identifies a user between requests;
  176. - Voter: sort of judge that returns if access is granted of denied, if the voter should not vote for a case, it returns abstrain;
  177. - AccessDecisionManager: decides if access is granted or denied according a specific strategy. It grants access if at least one (affirmative
  178. strategy), all (unanimous strategy) or more then half (consensus strategy) of the counted votes granted access;
  179. - RoleVoter: votes for all attributes stating with "ROLE_" and grants access if the user has this role;
  180. - RoleHierarchieVoter: when the role ROLE_SONATA_ADMIN is voted for, it also votes "granted" if the user has the role ROLE_SUPER_ADMIN;
  181. - AclVoter: grants access for the permissions of the Admin class if the user has the permission, the user has a permission that is
  182. included in the bitmasks of the permission requested to vote for or the user owns the object.
  183. Create a custom voter or a custom permission map
  184. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  185. In some occasions you need to create a custom voter or a custom permission map because for example you want to restrict access using extra rules:
  186. - create a custom voter class that extends the AclVoter
  187. .. code-block:: php
  188. namespace Acme\DemoBundle\Security\Authorization\Voter;
  189. use FOS\UserBundle\Model\UserInterface;
  190. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  191. use Symfony\Component\Security\Acl\Voter\AclVoter;
  192. class UserAclVoter extends AclVoter
  193. {
  194. /**
  195. * {@InheritDoc}
  196. */
  197. public function supportsClass($class)
  198. {
  199. // support the Class-Scope ACL for votes with the custom permission map
  200. // return $class === 'Sonata\UserBundle\Admin\Entity\UserAdmin' || $is_subclass_of($class, 'FOS\UserBundle\Model\UserInterface');
  201. // if you use php >=5.3.7 you can check the inheritance with is_a($class, 'Sonata\UserBundle\Admin\Entity\UserAdmin');
  202. // support the Object-Scope ACL
  203. return is_subclass_of($class, 'FOS\UserBundle\Model\UserInterface');
  204. }
  205. public function supportsAttribute($attribute)
  206. {
  207. return $attribute === 'EDIT' || $attribute === 'DELETE';
  208. }
  209. public function vote(TokenInterface $token, $object, array $attributes)
  210. {
  211. if (!$this->supportsClass(get_class($object))) {
  212. return self::ACCESS_ABSTAIN;
  213. }
  214. foreach ($attributes as $attribute) {
  215. if ($this->supportsAttribute($attribute) && $object instanceof UserInterface) {
  216. if ($object->isSuperAdmin() && !$token->getUser()->isSuperAdmin()) {
  217. // deny a non super admin user to edit a super admin user
  218. return self::ACCESS_DENIED;
  219. }
  220. }
  221. }
  222. // use the parent vote with the custom permission map:
  223. // return parent::vote($token, $object, $attributes);
  224. // otherwise leave the permission voting to the AclVoter that is using the default permission map
  225. return self::ACCESS_ABSTAIN;
  226. }
  227. }
  228. - optionally create a custom permission map, copy to start the Sonata\AdminBundle\Security\Acl\Permission\AdminPermissionMap.php to your bundle
  229. - declare the voter and permission map as a service
  230. .. code-block:: xml
  231. <!-- src/Acme/DemoBundle/Resources/config/services.xml -->
  232. <parameters>
  233. <parameter key="security.acl.user_voter.class">Acme\DemoBundle\Security\Authorization\Voter\UserAclVoter</parameter>
  234. <!-- <parameter key="security.acl.user_permission.map.class">Acme\DemoBundle\Security\Acl\Permission\UserAdminPermissionMap</parameter> -->
  235. </parameters>
  236. <services>
  237. <!-- <service id="security.acl.user_permission.map" class="%security.acl.permission.map.class%" public="false"></service> -->
  238. <service id="security.acl.voter.user_permissions" class="%security.acl.user_voter.class%" public="false">
  239. <tag name="monolog.logger" channel="security" />
  240. <argument type="service" id="security.acl.provider" />
  241. <argument type="service" id="security.acl.object_identity_retrieval_strategy" />
  242. <argument type="service" id="security.acl.security_identity_retrieval_strategy" />
  243. <argument type="service" id="security.acl.permission.map" />
  244. <argument type="service" id="logger" on-invalid="null" />
  245. <tag name="security.voter" priority="255" />
  246. </service>
  247. </services>
  248. - change the access decission strategy to ``unanimous``
  249. .. code-block:: yaml
  250. # app/config/security.yml
  251. security:
  252. access_decision_manager:
  253. # Strategy can be: affirmative, unanimous or consensus
  254. strategy: unanimous
  255. - to make this work the permission needs to be checked using the Object ACL
  256. - modify the template (or code) where applicable:
  257. .. code-block:: html
  258. {% if admin.isGranted('EDIT', user_object) %} {# ... #} {% endif %}
  259. - because the object ACL permission is checked, the ACL for the object must have been created, otherwise the AclVoter
  260. will deny EDIT access for a non super admin user trying to edit another non super admin user. This is automatically done when the object is
  261. created using the Admin. If objects are also created outside the Admin, have a look at the ``createSecurityObject`` method in the
  262. AclSecurityHandler.
  263. Usage
  264. ~~~~~
  265. Everytime you create a new ``Admin`` class, you should create start the command ``php app/console sonata:admin:setup-acl``
  266. so the ACL database will be updated with the latest roles and permissions.
  267. In the templates, or in your code, you can use the Admin method ``isGranted``:
  268. - check for an admin that the user is allowed to EDIT:
  269. .. code-block:: html
  270. {# use the admin security method #}
  271. {% if admin.isGranted('EDIT') %} {# ... #} {% endif %}
  272. {# or use the default is_granted symfony helper, the following will give the same result #}
  273. {% if is_granted('ROLE_SUPER_ADMIN') or is_granted('EDIT', admin) %} {# ... #} {% endif %}
  274. - check for an admin that the user is allowed to DELETE, the object is added to also check if the object owner is allowed to DELETE:
  275. .. code-block:: html
  276. {# use the admin security method #}
  277. {% if admin.isGranted('DELETE', object) %} {# ... #} {% endif %}
  278. {# or use the default is_granted symfony helper, the following will give the same result #}
  279. {% if is_granted('ROLE_SUPER_ADMIN') or is_granted('DELETE', object) %} {# ... #} {% endif %}