Symfony2 AJAX登录 [英] Symfony2 AJAX Login

查看:78
本文介绍了Symfony2 AJAX登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个示例,我尝试使用Symfony2和FOSUserBundle创建AJAX登录.我在security.yml文件的form_login下设置了自己的success_handlerfailure_handler.

I have an example where I am trying to create an AJAX login using Symfony2 and FOSUserBundle. I am setting my own success_handler and failure_handler under form_login in my security.yml file.

这是课程:

class AjaxAuthenticationListener 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;
        }
    }
}

这对于处理成功和失败的AJAX登录尝试都非常有用.但是,启用后-我无法通过标准表单POST方法(非AJAX)登录.我收到以下错误:

This works great for handling both successful and failed AJAX login attempts. However, when enabled - I am unable to login via the standard form POST method (non-AJAX). I receive the following error:

Catchable Fatal Error: Argument 1 passed to Symfony\Component\HttpKernel\Event\GetResponseEvent::setResponse() must be an instance of Symfony\Component\HttpFoundation\Response, null given

我希望我的onAuthenticationSuccessonAuthenticationFailure重写仅对XmlHttpRequests(AJAX请求)执行,如果没有,则将执行交还给原始处理程序.

I'd like for my onAuthenticationSuccess and onAuthenticationFailure overrides to only be executed for XmlHttpRequests (AJAX requests) and to simply hand the execution back to the original handler if not.

有没有办法做到这一点?

Is there a way to do this?

TL; DR我希望AJAX请求登录尝试以返回JSON响应以表示成功和失败,但是我希望它不影响通过POST表单进行的标准登录.

TL;DR I want AJAX requested login attempts to return a JSON response for success and failure but I want it to not affect standard login via form POST.

推荐答案

David的答案很好,但是缺少newb的细节很少-所以这是填补空白.

David's answer is good, but it's lacking a little detail for newbs - so this is to fill in the blanks.

除了创建AuthenticationHandler之外,还需要使用创建处理程序的捆绑软件中的服务配置将其设置为服务.默认的捆绑软件生成将创建一个xml文件,但我更喜欢yml.这是一个示例services.yml文件:

In addition to creating the AuthenticationHandler you'll need to set it up as a service using the service configuration in the bundle where you created the handler. The default bundle generation creates an xml file, but I prefer yml. Here's an example services.yml file:

#src/Vendor/BundleName/Resources/config/services.yml

parameters:
    vendor_security.authentication_handler: Vendor\BundleName\Handler\AuthenticationHandler

services:
    authentication_handler:
        class:  %vendor_security.authentication_handler%
        arguments:  [@router]
        tags:
            - { name: 'monolog.logger', channel: 'security' }

您需要修改DependencyInjection捆绑包扩展以使用yml而不是xml,如下所示:

You'd need to modify the DependencyInjection bundle extension to use yml instead of xml like so:

#src/Vendor/BundleName/DependencyInjection/BundleExtension.php

$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');

然后在应用程序的安全配置中,设置对您刚定义的authentication_handler服务的引用:

Then in your app's security configuration you set up the references to the authentication_handler service you just defined:

# app/config/security.yml

security:
    firewalls:
        secured_area:
            pattern:    ^/
            anonymous: ~
            form_login:
                login_path:  /login
                check_path:  /login_check
                success_handler: authentication_handler
                failure_handler: authentication_handler

这篇关于Symfony2 AJAX登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆