Symfony2 AJAX 登录 [英] Symfony2 AJAX Login

查看:24
本文介绍了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 SymfonyComponentSecurityHttpFirewallAbstractAuthenticationListener
     * @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:

可捕获的致命错误:传递给 SymfonyComponentHttpKernelEventGetResponseEvent::setResponse() 的参数 1 必须是 SymfonyComponentHttpFoundationResponse 的实例,给定为 null

我希望我的 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 的 answer 很好,但缺乏新手的小细节 - 所以这是填补空白.

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: VendorBundleNameHandlerAuthenticationHandler

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 LoaderYamlFileLoader($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天全站免登陆