This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

How to Implement FOSUserBundle in Symfony 3.1

Updated on December 8, 2021

5 Min Read

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.

implement FOSUserBundle in Symfony 3.1

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.

Launch SSH Terminal

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.

ssh terminal

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.

Enabling Bundle in AppKernel.php

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.

Updating Database Schema

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.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now