我是symfony的新手,我想在用户登录时返回一个json,但我不知道如何。 我正在使用一个带login_check的简单表单来验证我的数据库中的用户,我只想返回这个:
$response = new JsonResponse('borala', 200, array(
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Accept',
'Content-Type' => 'application/json'));
答案 0 :(得分:3)
因为login_check是一个幻像'实际上并不对应于控制器的路由,您需要使用自定义身份验证处理程序。以下是我完成的工作(简化):
处理程序
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface
{
protected $router;
protected $session;
public function __construct( RouterInterface $router, Session $session )
{
$this->router = $router;
$this->session = $session;
}
public function onAuthenticationFailure( Request $request, AuthenticationException $exception )
{
if( $request->isXmlHttpRequest() )
{
$response = new Response( json_encode( array( 'success' => false, 'message' => $exception->getMessage() ) ) );
$response->headers->set( 'Content-Type', 'application/json' );
return $response;
}
$request->getSession()->set( Security::AUTHENTICATION_ERROR, $exception );
return new RedirectResponse( $this->router->generate('site_login') );
}
public function onAuthenticationSuccess( Request $request, TokenInterface $token )
{
if( $request->isXmlHttpRequest() )
{
$response = new Response( json_encode( array( 'success' => true ) ) );
$response->headers->set( 'Content-Type', 'application/json' );
return $response;
}
$url = ( $this->session->get('_security.main.target_path') ) ? $this->session->get('_security.main.target_path') : $this->router->generate('home') ;
return new RedirectResponse( $url );
}
将处理程序设置为服务:
security.auth_handler:
class: MyNamespace\Service\Security\Listeners\AuthenticationHandler
public: false
arguments: ['@router','@session']
针对防火墙设置处理程序:
site:
...
form_login:
login_path: /login
check_path: /check_login
success_handler: security.auth_handler
failure_handler: security.auth_handler
logout:
path: /logout
target: /