Symfony 2.8 Jobeet Day 13: Security

Dragos Holban
5 min readAug 1, 2017

--

Securing the Application

Security is a two-step process whose goal is to prevent a user from accessing a resource that he/she should not have access to. In the first step of the process, the authentication, the security system identifies who the user is by requiring the user to submit some sort of identification. Once the system knows who you are, the next step, called the authorization, is to determine if you should have access to a given resource (it checks to see if you have privileges to perform a certain action).

The security component can be configured via your application configuration using the security.yml file from the app/config folder. To secure our application add the following to your security.yml file:

This configuration will secure the /admin section of the website (all urls that start with /admin) and will allow only users with ROLE_ADMIN to access it (see the access_control section). In this example the admin user is defined in the configuration file (the providers section) and the password is not encoded (encoders).

For authenticating users a traditional login form will be used, but we need to implement it. First, create two routes: one that will display the login form (i.e. /login) and one that will handle the login form submission (i.e. /login_check):

We will not need to implement a controller for the /login_check URL as the firewall will automatically catch and process any form submitted to this URL. It’s optional, but helpful, to create a route so that it can be used to generate the form submission URL in the login template below.

Next, let’s create the controller and the action that will display the login form:

When the user submits the form, the security system automatically handles the form submission for you. If the user had submitted an invalid username or password, this action reads the form submission error from the security system so that it can be displayed back to the user. Your only job is to display the login form and any login errors that may have occurred, but the security system itself takes care of checking the submitted username and password and authenticating the user.

Finally, let’s create the corresponding template:

Now, if you try to access http://jobeet.local/app_dev.php/admin/dashboard url, the login form will show and you will have to enter the username and password defined in security.yml (admin/adminpass) to get to the admin section of Jobeet.

User Providers

During authentication, the user submits a set of credentials (usually a username and password). The job of the authentication system is to match those credentials against some pool of users. So where does this list of users come from?

In Symfony 2, users can come from anywhere - a configuration file, a database table, a web service, or anything else you can dream up. Anything that provides one or more users to the authentication system is known as a “user provider”. Symfony 2 comes standard with the two most common user providers: one that loads users from a configuration file and one that loads users from a database table.

Above, we used the first case: specifying users in a configuration file:

But you will usually want the users to be stored in a database table. To do this we will add a new User entity to our Jobeet project:

Now run the doctrine:generate:entities command to generate setters and getters for the new User entity class:

php app/console doctrine:generate:entities AppBundle

And update the database:

php app/console doctrine:schema:update --force

The only requirement for your new user class is that it implements the UserInterface interface. This means that your concept of a “user” can be anything, as long as it implements this interface. Open the User.php file and edit it as follows:

To the generated entity we added the methods required by the UserInterface class: getRoles, getSalt and eraseCredentials.

Next, configure an entity user provider, and point it to your User class:

We also changed the encoder for our new User class to use the sha512 algorithm to encrypt passwords.

Now everything is set up but we need to create our first user. To do this we will create a new symfony command:

To add your first user run:

php app/console jobeet:users admin admin

This will create the admin user with the password admin. You can use it to login to the admin section.

Logout

Logging out is handled automatically by the firewall. All you have to do is to activate the logout config parameter:

And you’ll need to create a route for this URL (but not a controller):

Once this is configured under your firewall, sending a user to /logout (or whatever you configure the path to be), will un-authenticate the current user. The user will then be sent to the homepage (the value defined by the targetparameter).

All left to do is to add the logout link to our admin section. To do this we will override the user_block.html.twig from SonataAdminBundle. Create the user_block.html.twig file in app/Resources/SonataAdminBundle/views/Core folder:

Now, if you try to enter the admin section, you will be asked for an username and password and then, the logout link will be in the top-right corner user menu.

The User Session

Symfony 2 provides a nice session object that you can use to store information about the user between requests. You can store and retrieve information from the session easily from the controller:

Unfortunately, the Jobeet user stories have no requirement that includes storing something in the user session. So let’s add a new requirement: to ease job browsing, the last three jobs viewed by the user should be displayed in the menu with links to come back to the job page later on.

When a user access a job page, the displayed job object needs to be added in the user history and stored in the session:

In the base.html.twig template, add the following code before the #content div:

Flash Messages

Flash messages are small messages you can store on the user’s session for exactly one additional request. This is useful when processing a form: you want to redirect and have a special message shown on the next request. We already used flash messages in our project when we publish a job:

The first argument of the addFlash function is the identifier of the flash and the second one is the message to display. You can define whatever flashes you want, but notice and error are two of the more common ones.

To show the flash messages to the user you have to include them in the template. We did this in the base.html.twig template:

That’s all about security and user session. You can find the code from this post here: https://github.com/dragosholban/jobeet-sf2.8/tree/day13

About the Author

Passionate about web & mobile development. Doing this at IntelligentBee for the last 5 years. If you are looking for custom web and mobile app development, please contact us here and let’s have a talk.

--

--