## How To Add An AJAX Login Form To A Symfony2 Project

Categories : Article, Symfony

Adding an AJAX login form to a Symfony2 project is quite easy but it covers few things. The first thing is that the Symfony firewall handles authentications by sending a form to the route defined in the apps/config/security.yml as the check path for the firewall. So, if you want to login using AJAX, a form needs to be posted to that route along with few fields like username, password, remember me and if you have enabled CSRF for your form then the csrf token field. The firewall will then allow the user to login or reject it and will redirect to the login route or any of the routes set in the app/config/security.yml file.

The steps involved are:

Firstly, create a class that can handle authentication. It must implement the AuthenticationSuccessHandlerInterface and AuthenticationFailureHandlerInterface. The methods i.e onAuthenticationSuccess and onAuthenticationFailure will be called to handle authentication. If you wish to check the request to find out if its an AJAX call simply you need to call the isXmlHttpRequest() method and if it is an AJAX call you’ve to return a JSON response. If it isn’t then you’ve to return a RedirectResponse to appropriate destination. In the onAuthenticationFailure method you can even return a error message which will be displayed to the user.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 // AuthenticationHandler.php   namespace path\to\your\class;   use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\Routing\RouterInterface; use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\SecurityContextInterface; use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface; use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;   class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface {     private $router; private$session;       /**      * Constructor      *      * @author     Joe Sexton <joe@webtipblog.com>      * @param     RouterInterface $router * @param Session$session      */     public function __construct( RouterInterface $router, Session$session )     {         $this->router =$router;         $this->session =$session;     }    /**      * onAuthenticationSuccess      *      * @author     Joe Sexton <joe@webtipblog.com>      * @param     Request $request * @param TokenInterface$token      * @return     Response      */     public function onAuthenticationSuccess( Request $request, TokenInterface$token )     {         // if AJAX login         if ( $request->isXmlHttpRequest() ) {$array = array( 'success' => true ); // data to return via JSON             $response = new Response( json_encode($array ) );             $response->headers->set( 'Content-Type', 'application/json' ); return$response;           // if form login         } else {               if ( $this->session->get('_security.main.target_path' ) ) {$url = $this->session->get( '_security.main.target_path' ); } else {$url = $this->router->generate( 'home_page' ); } // end if return new RedirectResponse($url );           }     }       /**      * onAuthenticationFailure      *      * @author     Joe Sexton <joe@webtipblog.com>      * @param     Request $request * @param AuthenticationException$exception      * @return     Response      */      public function onAuthenticationFailure( Request $request, AuthenticationException$exception )     {         // if AJAX login         if ( $request->isXmlHttpRequest() ) {$array = array( 'success' => false, 'message' => $exception->getMessage() ); // data to return via JSON$response = new Response( json_encode( $array ) );$response->headers->set( 'Content-Type', 'application/json' );               return $response; / if form login } else { // set authentication exception to session$request->getSession()->set(SecurityContextInterface::AUTHENTICATION_ERROR, $exception); return new RedirectResponse($this->router->generate( 'login_route' ) );         }     } }

Next step is you’ve to register a service for this class  in your bundle’s Resources/config/services.yml file.

1 2 3 4 5 6 7 8 # Resources/config/services.yml   acme.security.authentication_handler:         class: path\to\your\class\AuthenticationHandler         public: false         arguments:             - @router             - @session

The final step is you’ve to register this service as the handler for authentication success and failure in the app/config/security.yml file. You’ve to simply add the success handler and failure handler parameters to your firewall configuration.

1 2 3 4 5 6 7 8 9 # app/config/security.yml   security:     firewalls:         main:             form_login:                 check_path:      security_check_route                 success_handler: acme.security.authentication_handler                 failure_handler: acme.security.authentication_handler

So, what keeps you waiting? Contact us today for Symfony Development Services…!

[Total: 2    Average: 5/5]

### Client Saying

We have dealt with a lot of web development firms and other tech support companies, none come close to Brainvire....
##### Mr. Matthew
###### CEO
Just wanted to say massive thanks for all the help from the Brainvire team. After years of having a website...
##### Mr. Rohit Singla
###### CEO
BIG THANK YOU to Brainvire team for all their smart work and fantastic services. We are very pleased with the...
##### Mr. Greg Pietsch
###### CEO
I just want to say it's truly worth investing in services of Brainvire. They gave me what I required and...
##### Mr. Vinay Saini
###### CTO
Chad Gundry, the CEO of Bragshare.com says that he has worked extensively with Brainvire team since last 6 to 7...