Hello, friends!!! How are you doing? Hope good. In this tutorial we will learn about Symfony authentication system. This tutorial is the continuation of previous Symfony tutorials. So, you may be puzzled if you do not complete previous posts. With Google Cloud compliance one can secure their system.
HTTP Authentication
The Security component can be configured via your application configuration. In fact, most standard security setups are just a matter of using the right configuration. There are five basic steps to configure Symfony security system:
-
- Configure security.yml file as needed
-
- Create your routing in routing.yml
-
- Create a security controller to SecurityController.php
-
- Create view for your login in
-
- Configure your page as needed
Let’s assume in our book inventory system, we want only admin can login, edit and delete all the books. Other normal users only can see the front page. Without login, they cannot do anything other then view the page.
So, let’s start.
Step 1: Configure security.yml file as needed
Open app/config/security.yml with your IDE. Write the following code segment after deleting, whatever you have before.
security: encoders: Symfony\Component\Security\Core\User\User: plaintext role_hierarchy: ROLE_ADMIN: [ROLE_USER] providers: chain_provider: chain: providers: [in_memory] in_memory: memory: users: admin: {password: adminpass, roles: ROLE_ADMIN} firewalls: main: pattern: /.* form_login: login_path: /login check_path: /login_check default_target_path: /book logout: path: /logout target: /book security: true anonymous: true access_control: - { path: /login, roles: IS_AUTHENTICATED_ANONYMOUSLY } - { path: /.*, roles: IS_AUTHENTICATED_ANONYMOUSLY }Don’t be scared most of the code is boilerplate code. What you need to concentrate is the access control. Rest of the code you can get from the documentation. In this code we have created five nodes:
encoders
-
-
- in line 2
-
role_hierarchy
-
-
- in 4
-
providers
-
-
- in line 6
-
firewalls
-
-
- in line 14
-
access_control
-
- in line 28
Step 2: Create your routing in routing.yml
Open src/custom/BookBundle/Resources/config/routing.yml and create three route for login, login check and logout.
custom_book_book: resource: "@CustomBookBundle/Resources/config/routing/book.yml" prefix: /book custom_book_homepage: path: /hello defaults: { _controller: CustomBookBundle:Default:index } login: path: /login defaults: { _controller: CustomBookBundle:Security:login } login_check: path: /login_check logout: pattern: /logoutFrom line 1-7 is already created for our previous tutorials. We need to add only from line 10-18. Here we have created the paths for our login, login_check and logout. We only need to create the functionality for our login. login_check and logout will be handled by our mighty Symfony.
Step 3: Create a security controller to SecurityController.php
Now create a new controller for our security, src/custom/BookBundle/Controller/SecurityController.php.namespace Custom\BookBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\SecurityContextInterface; class SecurityController extends Controller { public function loginAction(Request $request) { $session = $request->getSession(); // get the login error if there is one if ($request->attributes->has(SecurityContextInterface::AUTHENTICATION_ERROR)) { $error = $request->attributes->get( SecurityContextInterface::AUTHENTICATION_ERROR ); } elseif (null !== $session && $session->has(SecurityContextInterface::AUTHENTICATION_ERROR)) { $error = $session->get(SecurityContextInterface::AUTHENTICATION_ERROR); $session->remove(SecurityContextInterface::AUTHENTICATION_ERROR); } else { $error = ''; } return $this->render( 'CustomBookBundle:Security:login.html.twig', array( 'error' => $error, ) ); } }Step 4: Create view for your login in
So, you need to create a new folder called Security inside views and create a new twig file for your login. src/custom/BookBundle/Resources/views/Security/login.html.twig{% extends '::base.html.twig' %} {% block body %} {% if error %} <div>{{ error.message }}</div> {% endif %} <form action="{{ path('login_check') }}" method="post"> <label for="username">Username:</label> <input type="text" id="username" name="_username" /> <label for="password">Password:</label> <input type="password" id="password" name="_password" /> <button type="submit">login</button> </form> {% endblock %}Step 5: Configure your page as needed
In this step, most of the files are created before. We only modify some code segment for our purpose.Open app/Resources/views/base.html.twig with your IDE. I have given only fragment of code for our navbar. Rest of the code will be same.
<div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="{{ path('book') }}">Home</a></li> {% if is_granted('ROLE_ADMIN') %} <li><a href="{{ path('logout') }}">Logout</a></li> {% else %} <li><a href="{{ path('login') }}">Login</a></li> {% endif %} </ul> </div>In line 6 we have checked, if the admin is logged in or not. If logged in, the show the link for logout otherwise login menu item will be displayed.
Open src/Custom/BookBundle/Resources/views/Book/index.html.twig file.
{% extends '::base.html.twig' %} {% block body -%} <h1>Book list {% if is_granted('ROLE_ADMIN') %}<span><a class="btn btn-primary btn-lg" href="{{ path('book_new') }}" rold="button"> Create a new entry </a></span>{% endif %}</h1> <div class="table-responsive"> <table class="records_list table table-striped table-bordered"> <thead> <tr> {% if is_granted('ROLE_ADMIN') %} <th>Id</th> {% endif %} <th>Name</th> <th>Author</th> <th>Language</th> <th>Publisher</th> <th>Summary</th> {% if is_granted('ROLE_ADMIN') %} <th>Actions</th> {% endif %} </tr> </thead> <tbody> {% for entity in entities %} <tr> {% if is_granted('ROLE_ADMIN') %} <td><a href="{{ path('book_show', { 'id': entity.id }) }}">{{ entity.id }}</a></td> {% endif %} <td>{{ entity.name }}</td> <td>{{ entity.author }}</td> <td>{{ entity.language }}</td> <td>{{ entity.publisher }}</td> <td>{{ entity.summary }}</td> {% if is_granted('ROLE_ADMIN') %} <td style="text-align: center; vertical-align: middle;"> <ul style="list-style-type: none;"> <li> <a class="btn btn-default btn-xs" href="{{ path('book_show', { 'id': entity.id }) }}">show</a> </li> <li style="margin-top: 10px;"> <a class="btn btn-default btn-xs" href="{{ path('book_edit', { 'id': entity.id }) }}">edit</a> </li> </ul> </td> {% endif %} </tr> {% endfor %} </tbody> </table> </div> {% endblock %}Before there were seven columns in our index view. But only admin can see the all the seven columns. Others will not see two columns which are for view and edit and delete. That’s why we have checked the credentials in line 4, 13, 21, 29 and 37. Rest of the code will be same.
We are all done.
Now open your browser and go to http://localhost/symfony/web/app_dev.php/book/. Login with:
User name: admin
Password: adminpassThis page is for anonymous user–
After login the admin will see the following page –
By the way, you can download all the code from my –
Happy coding…
Login and Authentication with Symfony
Hej, I’m from Bangladesh. Learning programming is one of the freaking decisions I have taken in my life. Because, it makes me and my life crazy. I have great weakness on open source technologies. Perhaps, that’s why I do not know any closed source language. I fall in love with programming, when I started my undergraduate in East West University. Till now, I can not live without it.
I have read so many articles or reviews on the topic of the blogger lovers however this post is actually a pleasant post, keep it up.
Nice post. I was checking constantly this weblog and I am impressed! Very useful info specifically the remaining part 🙂 I handle such info much. I used to be seeking this certain information for a long time. Thanks and best of luck.
Nice post! but after implementing everything when I logout and hit the browser back button; it goes back to the site which mean the session of that user is not destroy.
How can that be accomplish?
Nice tutorial. But, why you didn’t use FOSUserBundle for implementing authentication? I read a tutorial on Cloudways blog on implementing auth in symfony, they used auto0 and FOSUserBundle. The process was quite easy and simple.
I am truly happy to glance at this website posts which consists of plenty of useful facts, thanks for providing such information.
Nice blog right here! Additionally your web site so much up fast! What web host are you the usage of? Can I get your affiliate hyperlink for your host? I want my website loaded up as quickly as yours lol
Fantastic beat ! I wish to apprentice while you amend your website, how can i subscribe for a blog site? The account helped me a acceptable deal. I had been tiny bit acquainted of this your broadcast provided bright clear concept
excellent publish, very informative. I wonder why the opposite specialists of this sector don’t understand this. You should continue your writing. I am sure, you’ve a great readers’ base already!