In the later installment of this Symfony 3 series, I have talked about Overriding Default FOSUserBundle Templates and Overriding The Default Registration Form
User registration and login management is one of the most common aspect of any framework. Almost every framework offers its own system of user registration and management of users.
In the case of Symfony, there is a very remarkable implementation of this idea in the form of a bundle called FOSUserBundle. This bundle is ideal for designing and implementing user registration and login in a web app. FOSUserBundle allows developer to load and store user credentials from any data source including from configuration and databases. Symfony also introduces some new features in latest release.
In this blog, I will show how to implement this bundle in Symfony 3.1. Please note that if you are using Symfony2, you must use version 1.2 of the bundle. If you havn’t install symfony yet than read How you can install symfony on Cloudways.
Install FOSUserBundle In the Project
First, I will demonstrate how to install the bundle on the Cloudways server using composer.
Login to SSH terminal using master credentials.
After login, move to your application folder and run this command using the composer.
Note:Â We are using dev version of bundle here because of compatibility issues with symfony 3.1 you can see the github issue here.
$ composer require friendsofsymfony/user-bundle "~2.0@dev"
This command will install FOSUserBundle in the project.
Composer.JSON will update itself and install all the newly added dependencies in the Symfony project. Composer will install the bundle at:
vendor/friendsofsymfony/user-bundle.
You could see that the bundle has been successfully installed in the project.
Enabling Bundle in AppKernel.php
After installing FOSUserBundle you must enable it in the project. Go to app/config/AppKernel.php and add the highlighted line in the bundles array. Save it.
Creating User entity in Project
Now we need to create an entity class USER to work with our database. Previously we have see how we can create entity in Symfony project by using the Doctrine command. I will show you another manual method for creating database entity. Move to src/AppBundle and create a folder with the name Entity. In the Entity folder, create a file User.php and paste the following code in it.
<?php // src/AppBundle/Entity/User.php namespace AppBundle\Entity; use FOS\UserBundle\Model\User as BaseUser; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="fos_user") */ class User extends BaseUser { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; public function __construct() { parent::__construct(); // your own logic } }
This class will interact with the database according to your implemented methods. This class will create a table in the database with the name of fos_user. We are using doctrine ORM so the User class will lie under Entity namespace.
Configuring Security.yml file
Symfony security component should know about FOSUserBundle to use it properly. Hence, we need to configure security.yml file in the project. Open the file and override the following code in it
# app/config/security.yml security: encoders: FOS\UserBundle\Model\UserInterface: bcrypt role_hierarchy: ROLE_ADMIN: ROLE_USER ROLE_SUPER_ADMIN: ROLE_ADMIN providers: fos_userbundle: id: fos_user.user_provider.username firewalls: main: pattern: ^/ form_login: provider: fos_userbundle csrf_token_generator: security.csrf.token_manager # if you are using Symfony < 2.8, use the following config instead: # csrf_provider: form.csrf_provider logout: true anonymous: true access_control: - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/admin/, role: ROLE_ADMIN }
In the provider section, I enabled the bundle for users. The firewall section acts as an auth checkpoint by authenticating the user’s credentials and redirecting them to respective page, either login or registration. Symfony security firewall can also implement other authentication methods like OAuth2. In the access control section, user paths are defined that redirect users on a specific request. User roles also defined here.
Configure FOSUserBundle in a Config
Now that the security file has been configured according to the bundle’s needs and requirement, I need to configure the user bundle in the Config file so that it can interact with the Doctrine driver. Open app/config/config.yml and add the following code:
fos_user: db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel' firewall_name: main user_class: AppBundle\Entity\User
Since we are using Doctrine, the database driver will be orm.
Importing Route files of FOSUserBundle
We have successfully configured and activate all the settings for the bundle. I will now import all the required files such as  login, register and reset. All these files can be imported by adding the following code in Routing.yml file. Go to app/config/routing.yml and add the following code in it.
fos_user: resource: "@FOSUserBundle/Resources/config/routing/all.xml"
This command will import all the files in Symfony core for proper usage.
Updating Database Schema
The last step is to update the database schema to create table in the database. I created the entity User for this.
To update the schema, type this command in SSH terminal.
php bin/console doctrine:schema:update --force
You can see the update message below.
Open the database userdata and  you can see the table fos_user created there.
So we have successfully integrate FOSUserbundle in our symfony project now open your browser and hit the Application URL and add /login or /register in the end.
You will see the login form will open. First register yourself and then login.
Go to the registration page and register as a test user. Next try to log in.
Final Words
This blog explains the complete installation and basic configuration of FOSUserBundle in a test project. The project is tested by registering and login of a test user. This project does not show the full extent of the capabilities of  FOSUserbundle. Some ideas include overriding the default template, hooking in the controllers, overriding the default controllers check out the  Symfony official website for more ideas.
In the next part of this series, I will highlight how Symfony 3.1 manages user authentication using Auth0. Here is a short introduction and list of major topics in this Symfony 3.1 series.
If you have a query or an idea about this test project, please leave a comment.
Shahroze Nawaz
Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling.