2016-05-20 4 views
2

Я хочу, чтобы участники регистрировались в интерфейсе, и я определил свой обработчик проверки подлинности ниже и добавил его как службу, которая дает мне ответ json, как и ожидалось.Symfony3 и Ajax Authentication

<?php 

namespace AppBundle\Handler; 

use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface; 
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface; 
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; 
use Symfony\Component\Routing\RouterInterface; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpFoundation\Response; 
use Symfony\Component\HttpFoundation\RedirectResponse; 
use Symfony\Component\Routing\Router; 
use Symfony\Component\Security\Core\SecurityContext; 
use Symfony\Component\Security\Core\Exception\AuthenticationException; 


class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface 
{ 

protected $router; 
//protected $security; 
protected $userManager; 
protected $service_container; 

public function __construct(RouterInterface $router, $userManager, $service_container) 
{ 
    $this->router = $router; 
    //$this->security = $security; 
    $this->userManager = $userManager; 
    $this->service_container = $service_container; 

} 
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; 
    } 
    else { 
     // Create a flash message with the authentication error message 
     $request->getSession()->set(SecurityContext::AUTHENTICATION_ERROR, $exception); 
     $url = $this->router->generate('fos_user_security_login'); 

     return new RedirectResponse($url); 
    } 

    return new RedirectResponse($this->router->generate('anag_new')); 
} 
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; 
    } 
    return new Response(); 
} 
} 

Однако, я получаю такие же результаты независимо от того, зарегистрирован пользователь или нет. Вот ответ

{"success":false,"message":"Bad credentials."} 

Вот мой security.yml

firewalls: 
    # disables authentication for assets and the profiler, adapt it according to your needs 
    dev: 
     pattern: ^/(_(profiler|wdt)|css|images|js)/ 
     security: false 

    admin: 
     pattern:   /admin(.*) 
     context:   user 
     form_login: 
      provider:  fos_userbundle 
      login_path:  /admin/login 
      use_forward: false 
      check_path:  /admin/login_check 
      failure_path: null 
     logout: 
      path:   /admin/logout 
      target:   /admin/login 
     anonymous:   true 

    main: 
     pattern:    .* 
     context:    user 
     form_login: 
      provider:  fos_userbundle 
      login_path:  /login 
      use_forward: false 
      check_path:  fos_user_security_check 
      failure_path: null 
      success_handler: authentication_handler 
      failure_handler: authentication_handler 
     logout:    true 
     anonymous:   true 

routing.yml

fos_user_security_check: 
    path: /login_check 
    defaults: 
     _controller: FOSUserBundle:Security:check 

fos_user_security_logout: 
    path: /logout 
    defaults: 
     _controller: FOSUserBundle:Security:logout 

ответ

0

esiest способ осуществления аутентификации API для меня, чтобы реализовать новую гвардию Интерфейс аутентификации

http://symfony.com/doc/current/cookbook/security/guard-authentication.html

Этот простой класс позволяет определить процесс, который создает экземпляр, обрабатывает и проверяет подлинность после обработки.

Включение службы так же легко, как

# app/config/security.yml 
security: 
    # ... 

    firewalls: 
     # ... 

     main: 
      anonymous: ~ 
      logout: ~ 

      guard: 
       authenticators: 
        - app.my_authenticator 

      # if you want, disable storing the user in the session 
      # stateless: true 

      # maybe other things, like form_login, remember_me, etc 
      # ... 

Кроме того, необходимо пользователю предоставить для этого

http://symfony.com/doc/current/cookbook/security/custom_provider.html

Использование Guard Вы можете обрабатывать любой тип пользовательской аутентификации (носителя, форм , файлы cookie, GET и т. д.)