index.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. Getting Started With FOSUserBundle
  2. ==================================
  3. The Symfony Security component provides a flexible security framework that
  4. allows you to load users from configuration, a database, or anywhere else
  5. you can imagine. The FOSUserBundle builds on top of this to make it quick
  6. and easy to store users in a database.
  7. So, if you need to persist and fetch the users in your system to and from
  8. a database, then you're in the right place.
  9. Prerequisites
  10. -------------
  11. This version of the bundle requires Symfony 2.1+. If you are using Symfony
  12. 2.0.x, please use the 1.2.x releases of the bundle.
  13. Translations
  14. ~~~~~~~~~~~~
  15. If you wish to use default texts provided in this bundle, you have to make
  16. sure you have translator enabled in your config.
  17. .. code-block:: yaml
  18. # app/config/config.yml
  19. framework:
  20. translator: ~
  21. For more information about translations, check `Symfony documentation`_.
  22. Installation
  23. ------------
  24. Installation is a quick (I promise!) 7 step process:
  25. 1. Download FOSUserBundle using composer
  26. 2. Enable the Bundle
  27. 3. Create your User class
  28. 4. Configure your application's security.yml
  29. 5. Configure the FOSUserBundle
  30. 6. Import FOSUserBundle routing
  31. 7. Update your database schema
  32. Step 1: Download FOSUserBundle using composer
  33. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  34. Require the bundle with composer:
  35. .. code-block:: bash
  36. $ composer require friendsofsymfony/user-bundle "~1.3"
  37. Composer will install the bundle to your project's ``vendor/friendsofsymfony/user-bundle`` directory.
  38. Step 2: Enable the bundle
  39. ~~~~~~~~~~~~~~~~~~~~~~~~~
  40. Enable the bundle in the kernel::
  41. <?php
  42. // app/AppKernel.php
  43. public function registerBundles()
  44. {
  45. $bundles = array(
  46. // ...
  47. new FOS\UserBundle\FOSUserBundle(),
  48. // ...
  49. );
  50. }
  51. Step 3: Create your User class
  52. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  53. The goal of this bundle is to persist some ``User`` class to a database (MySql,
  54. MongoDB, CouchDB, etc). Your first job, then, is to create the ``User`` class
  55. for your application. This class can look and act however you want: add any
  56. properties or methods you find useful. This is *your* ``User`` class.
  57. The bundle provides base classes which are already mapped for most fields
  58. to make it easier to create your entity. Here is how you use it:
  59. 1. Extend the base ``User`` class (the class to use depends of your storage)
  60. 2. Map the ``id`` field. It must be protected as it is inherited from the parent class.
  61. .. caution::
  62. When you extend from the mapped superclass provided by the bundle, don't
  63. redefine the mapping for the other fields as it is provided by the bundle.
  64. In the following sections, you'll see examples of how your ``User`` class should
  65. look, depending on how you're storing your users (Doctrine ORM, MongoDB ODM,
  66. or CouchDB ODM).
  67. .. note::
  68. The doc uses a bundle named ``AppBundle`` according to the Symfony best
  69. practices. However, you can of course place your user class in the bundle
  70. you want.
  71. .. caution::
  72. If you override the __construct() method in your User class, be sure
  73. to call parent::__construct(), as the base User class depends on
  74. this to initialize some fields.
  75. a) Doctrine ORM User class
  76. ..........................
  77. If you're persisting your users via the Doctrine ORM, then your ``User`` class
  78. should live in the ``Entity`` namespace of your bundle and look like this to
  79. start:
  80. .. configuration-block::
  81. .. code-block:: php-annotations
  82. <?php
  83. // src/AppBundle/Entity/User.php
  84. namespace AppBundle\Entity;
  85. use FOS\UserBundle\Entity\User as BaseUser;
  86. use Doctrine\ORM\Mapping as ORM;
  87. /**
  88. * @ORM\Entity
  89. * @ORM\Table(name="fos_user")
  90. */
  91. class User extends BaseUser
  92. {
  93. /**
  94. * @ORM\Id
  95. * @ORM\Column(type="integer")
  96. * @ORM\GeneratedValue(strategy="AUTO")
  97. */
  98. protected $id;
  99. public function __construct()
  100. {
  101. parent::__construct();
  102. // your own logic
  103. }
  104. }
  105. .. code-block:: yaml
  106. # src/AppBundle/Resources/config/doctrine/User.orm.yml
  107. AppBundle\Entity\User:
  108. type: entity
  109. table: fos_user
  110. id:
  111. id:
  112. type: integer
  113. generator:
  114. strategy: AUTO
  115. .. code-block:: xml
  116. <?xml version="1.0" encoding="utf-8"?>
  117. <!-- src/AppBundle/Resources/config/doctrine/User.orm.xml -->
  118. <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
  119. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  120. xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  121. <entity name="AppBundle\Entity\User" table="fos_user">
  122. <id name="id" type="integer" column="id">
  123. <generator strategy="AUTO"/>
  124. </id>
  125. </entity>
  126. </doctrine-mapping>
  127. .. caution::
  128. ``user`` is a reserved keyword in the SQL standard. If you need to use reserved words, surround them with backticks, *e.g.* ``@ORM\Table(name="`user`")``
  129. b) MongoDB User class
  130. .....................
  131. If you're persisting your users via the Doctrine MongoDB ODM, then your ``User``
  132. class should live in the ``Document`` namespace of your bundle and look like
  133. this to start::
  134. <?php
  135. // src/AppBundle/Document/User.php
  136. namespace AppBundle\Document;
  137. use FOS\UserBundle\Document\User as BaseUser;
  138. use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
  139. /**
  140. * @MongoDB\Document
  141. */
  142. class User extends BaseUser
  143. {
  144. /**
  145. * @MongoDB\Id(strategy="auto")
  146. */
  147. protected $id;
  148. public function __construct()
  149. {
  150. parent::__construct();
  151. // your own logic
  152. }
  153. }
  154. c) CouchDB User class
  155. .....................
  156. If you're persisting your users via the Doctrine CouchDB ODM, then your ``User``
  157. class should live in the ``CouchDocument`` namespace of your bundle and look
  158. like this to start::
  159. <?php
  160. // src/AppBundle/CouchDocument/User.php
  161. namespace AppBundle\CouchDocument;
  162. use FOS\UserBundle\Document\User as BaseUser;
  163. use Doctrine\ODM\CouchDB\Mapping\Annotations as CouchDB;
  164. /**
  165. * @CouchDB\Document
  166. */
  167. class User extends BaseUser
  168. {
  169. /**
  170. * @CouchDB\Id
  171. */
  172. protected $id;
  173. public function __construct()
  174. {
  175. parent::__construct();
  176. // your own logic
  177. }
  178. }
  179. d) Propel 1.x User class
  180. ........................
  181. If you don't want to add your own logic in your user class, you can simply use
  182. ``FOS\UserBundle\Propel\User`` as user class and you don't have to create
  183. another class.
  184. If you want to add your own fields, you can extend the model class by overriding the database schema.
  185. Just copy the ``Resources/config/propel/schema.xml`` file to ``app/Resources/FOSUserBundle/config/propel/schema.xml``,
  186. and customize it to fit your needs.
  187. Step 4: Configure your application's security.yml
  188. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  189. In order for Symfony's security component to use the FOSUserBundle, you must
  190. tell it to do so in the ``security.yml`` file. The ``security.yml`` file is where the
  191. basic security configuration for your application is contained.
  192. Below is a minimal example of the configuration necessary to use the FOSUserBundle
  193. in your application:
  194. .. code-block:: yaml
  195. # app/config/security.yml
  196. security:
  197. encoders:
  198. FOS\UserBundle\Model\UserInterface: bcrypt
  199. role_hierarchy:
  200. ROLE_ADMIN: ROLE_USER
  201. ROLE_SUPER_ADMIN: ROLE_ADMIN
  202. providers:
  203. fos_userbundle:
  204. id: fos_user.user_provider.username
  205. firewalls:
  206. main:
  207. pattern: ^/
  208. form_login:
  209. provider: fos_userbundle
  210. csrf_provider: security.csrf.token_manager # Use form.csrf_provider instead for Symfony <2.4
  211. logout: true
  212. anonymous: true
  213. access_control:
  214. - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
  215. - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
  216. - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
  217. - { path: ^/admin/, role: ROLE_ADMIN }
  218. Under the ``providers`` section, you are making the bundle's packaged user provider
  219. service available via the alias ``fos_userbundle``. The id of the bundle's user
  220. provider service is ``fos_user.user_provider.username``.
  221. Next, take a look at and examine the ``firewalls`` section. Here we have
  222. declared a firewall named ``main``. By specifying ``form_login``, you have
  223. told the Symfony Framework that any time a request is made to this firewall
  224. that leads to the user needing to authenticate himself, the user will be
  225. redirected to a form where he will be able to enter his credentials. It should
  226. come as no surprise then that you have specified the user provider service
  227. we declared earlier as the provider for the firewall to use as part of the
  228. authentication process.
  229. .. note::
  230. Although we have used the form login mechanism in this example, the FOSUserBundle
  231. user provider service is compatible with many other authentication methods
  232. as well. Please read the Symfony Security component documentation for
  233. more information on the other types of authentication methods.
  234. The ``access_control`` section is where you specify the credentials necessary for
  235. users trying to access specific parts of your application. The bundle requires
  236. that the login form and all the routes used to create a user and reset the password
  237. be available to unauthenticated users but use the same firewall as
  238. the pages you want to secure with the bundle. This is why you have specified that
  239. any request matching the ``/login`` pattern or starting with ``/register`` or
  240. ``/resetting`` have been made available to anonymous users. You have also specified
  241. that any request beginning with ``/admin`` will require a user to have the
  242. ``ROLE_ADMIN`` role.
  243. For more information on configuring the ``security.yml`` file please read the Symfony
  244. `security component documentation`_.
  245. .. note::
  246. Pay close attention to the name, ``main``, that we have given to the
  247. firewall which the FOSUserBundle is configured in. You will use this
  248. in the next step when you configure the FOSUserBundle.
  249. Step 5: Configure the FOSUserBundle
  250. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  251. Now that you have properly configured your application's ``security.yml`` to work
  252. with the FOSUserBundle, the next step is to configure the bundle to work with
  253. the specific needs of your application.
  254. Add the following configuration to your ``config.yml`` file according to which type
  255. of datastore you are using.
  256. .. configuration-block::
  257. .. code-block:: yaml
  258. # app/config/config.yml
  259. fos_user:
  260. db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
  261. firewall_name: main
  262. user_class: AppBundle\Entity\User
  263. .. code-block:: xml
  264. <!-- app/config/config.xml -->
  265. <!-- other valid 'db-driver' values are 'mongodb' and 'couchdb' -->
  266. <fos_user:config
  267. db-driver="orm"
  268. firewall-name="main"
  269. user-class="AppBundle\Entity\User"
  270. />
  271. Only three configuration values are required to use the bundle:
  272. * The type of datastore you are using (``orm``, ``mongodb``, ``couchdb`` or ``propel``).
  273. * The firewall name which you configured in Step 4.
  274. * The fully qualified class name (FQCN) of the ``User`` class which you created in Step 3.
  275. .. caution::
  276. When using one of the Doctrine implementation, you need either to use
  277. the ``auto_mapping`` option of the corresponding bundle (done by default
  278. for DoctrineBundle in the standard distribution) or to activate the mapping
  279. for FOSUserBundle otherwise the base mapping will be ignored.
  280. Step 6: Import FOSUserBundle routing files
  281. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  282. Now that you have activated and configured the bundle, all that is left to do is
  283. import the FOSUserBundle routing files.
  284. By importing the routing files you will have ready made pages for things such as
  285. logging in, creating users, etc.
  286. .. configuration-block::
  287. .. code-block:: yaml
  288. # app/config/routing.yml
  289. fos_user_security:
  290. resource: "@FOSUserBundle/Resources/config/routing/security.xml"
  291. fos_user_profile:
  292. resource: "@FOSUserBundle/Resources/config/routing/profile.xml"
  293. prefix: /profile
  294. fos_user_register:
  295. resource: "@FOSUserBundle/Resources/config/routing/registration.xml"
  296. prefix: /register
  297. fos_user_resetting:
  298. resource: "@FOSUserBundle/Resources/config/routing/resetting.xml"
  299. prefix: /resetting
  300. fos_user_change_password:
  301. resource: "@FOSUserBundle/Resources/config/routing/change_password.xml"
  302. prefix: /profile
  303. .. code-block:: xml
  304. <!-- app/config/routing.xml -->
  305. <import resource="@FOSUserBundle/Resources/config/routing/security.xml"/>
  306. <import resource="@FOSUserBundle/Resources/config/routing/profile.xml" prefix="/profile" />
  307. <import resource="@FOSUserBundle/Resources/config/routing/registration.xml" prefix="/register" />
  308. <import resource="@FOSUserBundle/Resources/config/routing/resetting.xml" prefix="/resetting" />
  309. <import resource="@FOSUserBundle/Resources/config/routing/change_password.xml" prefix="/profile" />
  310. .. note::
  311. In order to use the built-in email functionality (confirmation of the account,
  312. resetting of the password), you must activate and configure the SwiftmailerBundle.
  313. Step 7: Update your database schema
  314. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  315. Now that the bundle is configured, the last thing you need to do is update your
  316. database schema because you have added a new entity, the ``User`` class which you
  317. created in Step 4.
  318. For ORM run the following command.
  319. .. code-block:: bash
  320. $ php app/console doctrine:schema:update --force
  321. For MongoDB users you can run the following command to create the indexes.
  322. .. code-block:: bash
  323. $ php app/console doctrine:mongodb:schema:create --index
  324. For Propel 1 users you have to install the `TypehintableBehavior`_
  325. before to build your model. First, install it:
  326. .. code-block:: bash
  327. composer require willdurand/propel-typehintable-behavior
  328. You now can run the following command to create the model:
  329. .. code-block:: bash
  330. $ php app/console propel:build
  331. .. note::
  332. To create SQL, run the command ``propel:build --insert-sql`` or use migration
  333. commands if you have an existing schema in your database.
  334. You now can login at ``http://app.com/app_dev.php/login``!
  335. Next Steps
  336. ~~~~~~~~~~
  337. Now that you have completed the basic installation and configuration of the
  338. FOSUserBundle, you are ready to learn about more advanced features and usages
  339. of the bundle.
  340. The following documents are available:
  341. .. toctree::
  342. :maxdepth: 1
  343. overriding_templates
  344. overriding_controllers
  345. overriding_forms
  346. user_manager
  347. command_line_tools
  348. logging_by_username_or_email
  349. form_type
  350. emails
  351. groups
  352. doctrine
  353. overriding_validation
  354. canonicalizer
  355. custom_storage_layer
  356. configuration_reference
  357. adding_invitation_registration
  358. .. _security component documentation: https://symfony.com/doc/current/book/security.html
  359. .. _Symfony documentation: https://symfony.com/doc/current/book/translation.html
  360. .. _TypehintableBehavior: https://github.com/willdurand/TypehintableBehavior