What is required for json response from server?
/AppBundle/Handler/AuthenticationHandler.php
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 |
<?php namespace AppBundle\Handler; use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface; use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface { /** * This is called when an interactive authentication attempt succeeds. This * is called by authentication listeners inheriting from * AbstractAuthenticationListener. * * @see \Symfony\Component\Security\Http\Firewall\AbstractAuthenticationListener * @param Request $request * @param TokenInterface $token * @return Response the response to return */ public function onAuthenticationSuccess(Request $request, TokenInterface $token) { if ($request->isXmlHttpRequest()) { $result = array('success' => true); $response = new Response(json_encode($result)); $response->headers->set('Content-Type', 'application/json'); return $response; } } /** * This is called when an interactive authentication attempt fails. This is * called by authentication listeners inheriting from * AbstractAuthenticationListener. * * @param Request $request * @param AuthenticationException $exception * @return Response the response to return */ public function onAuthenticationFailure(Request $request, AuthenticationException $exception) { if ($request->isXmlHttpRequest()) { $result = array('success' => false, 'message' => $exception->getMessage()); $response = new Response(json_encode($result)); $response->headers->set('Content-Type', 'application/json'); return $response; } } } |
/AppBundle/Resources/config/services.yml
1 2 3 4 5 6 7 8 |
services: authentication_handler: class: AppBundle\Handler\AuthenticationHandler arguments: [ "@router" ] tags: - { name: 'monolog.logger', channel: 'security' } |
/app/config/security.yml
1 2 3 4 5 6 7 8 |
security: firewalls: main: form_login: success_handler: authentication_handler failure_handler: authentication_handler |
How to send login request?
You can use jquery for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$.ajax("urlToRoute:fos_user_security_check", { cache: false, data: "_username=SomeUsername&_password=YourPassword&_csrf_token=TokenValue", type: "POST", success: function (response) { if (response.success) { alert("Login successfull"); return; } alert(response.message); }, error: function (response) { console.log(response); alert("Something went wrong. Try again..."); } }); |