0

我正在 symfony2 中为我的登录表单实现一个对话框,它运行良好,除了我想用更多逻辑处理返回,现在我不知道该怎么做,因为防火墙配置会接收登录提交。

发生的情况是,如果登录失败,我的对话框的 html 将被登录控制器返回的新 html 替换,这一切都很好。但是如果成功登录尝试,我的登录对话框的 html 将替换为我的整个站点(因为成功的 symfony2 登录将重定向到起始页......)。

在平面 PHP 中,我会将其添加到登录控制器

if (login_successful) {
  return "success";
}

并在我的对话功能中放

if (returned_data == "success") {
  refresh_page(); // or location.href('something')
}
else
{
  // replace dialog_html with the returned html
}

但是,当我查看处理登录表单提交 i FOS 用户捆绑包的操作时,这就是我发现的

public function checkAction()
{
    throw new \RuntimeException('You must configure the check path to be handled by the firewall using form_login in your security firewall configuration.');
}

所以我意识到这一切都是在 symfony2 的幕后处理的,那我能做到吗?

实际示例代码(JS)...

function submitFormWithAjax(form) {
  form = $(form);
  $.ajax({
    url: form.attr('action'),
    data: form.serialize(),
    type: (form.attr('method')),
    dataType: 'html',
    success: function(data) {
        if (data == 'success') {
            //Success-token is passed, so reload page (will close dialog and load the logged-in start screen since user is now fully authenticated
            location.reload();
        }
        else {
            //Form is returned, probably with errors, so let user try again...
            $('#formDialog').html(data);
        }
      }
  });
  return false;
} 

和形式...

<form action="{{ path("fos_user_security_check") }}" method="post" id="login-form">
    <input type="hidden" name="_csrf_token" value="{{ csrf_token }}" />

    <TABLE>
        <TR>
            <TD><label for="username">Login</label></TD>
            <TD><input type="text" placeholder="användare" id="username" name="_username" value="{{ last_username }}" /></TD>
        </TR>
        <TR>
            <TD><label for="password">Lösenord</label></TD>
            <TD><input type="password" placeholder="lösenord" id="password" name="_password" /></TD>
        </TR>
        <TR>
            <TD><label for="remember_me">Kom ihåg mig</label></TD>
            <TD><input type="checkbox" id="remember_me" name="_remember_me" value="on" /></TD>
        </TR>
        <!--
        <TR>
            <TD></TD>
            <TD align="right"><input type="submit" id="_submit" name="_submit" value="Logga in" /></TD>
        </TR>
        -->
    </TABLE>

</form>

根据下面的 m2mdas 建议,我现在设置了这些:

配置.yml

#My services
services:
    my.authentication.success_handler:
        class:     Hemekonomi\UserBundle\AuthenticationSuccessHandler
        parent:    security.authentication.success_handler  

我的 userbundle 现在有这个类

<?php
namespace MyApp\UserBundle;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationSuccessHandler;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;

class AuthenticationSuccessHandler extends DefaultAuthenticationSuccessHandler
{
   public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        if(true === $request->isXmlHttpRequest()) {
            return new Response("success");
        }

        //default redirect operation.
        return parent::onAuthenticationSuccess($request, $token);
    }

}

...而security.yml具有...

firewalls:
    main:
        pattern: ^/
        form_login:
            provider: fos_userbundle
            csrf_provider: form.csrf_provider
            success_handler: my.authentication.success_handler
        logout:       true
        anonymous:    true

我得到的错误是这个

RuntimeException: The parent definition "security.authentication.success_handler" defined for definition "my.authentication.success_handler" does not exist.

它可能与格式有关,它在 xml/yml 中是否不同?我也不是这方面的专家,所以......

4

2 回答 2

1

您可以使用防火墙配置success_handlerfailure_handler选项。例如

成功处理程序类,

namespace Your\NameSpace;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationSuccessHandler;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;

class AuthenticationSuccessHandler extends DefaultAuthenticationSuccessHandler
{
   public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        if(true === $request->isXmlHttpRequest()) {
            return new Response("success");
        }

        //default redirect operation.
        return parent::onAuthenticationSuccess($request, $token);
    }

}

故障处理程序类,

namespace Your\NameSpace;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationFailureHandler;
use Symfony\Component\Security\Core\Exception\AuthenticationException;

class AuthenticationFailureHandler extends DefaultAuthenticationFailureHandler
{
    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        if(true === $request->isXmlHttpRequest()) {
            return new Response("failure");
        }

        //default redirect operation.
        return parent::onAuthenticationFailure($request, $exception);

    }
}

服务定义(xml)

    <service id="my.authentication.success_handler" class="Your\NameSpace\AuthenticationSuccessHandler" parent="security.authentication.success_handler"/>

    <service id="my.authentication.failure_handler" class="Your\NameSpace\AuthenticationFailureHandler" parent="security.authentication.failure_handler"/>

或者,yml 服务定义,

my.authentication.success_handler:
    class: Your\NameSpace\AuthenticationSuccessHandler
    parent: security.authentication.success_handler

my.authentication.failure_handler:
    class: Your\NameSpace\AuthenticationFailureHandler
    parent: security.authentication.failure_handler

最后在security.yml,

security:
    firewall:
        your_firewall:
            #...
            form_login:
                #...
                success_handler: my.authentication.success_handler
                failure_handler: my.authentication.failure_handler
于 2012-12-03T22:02:45.803 回答
0

我最终使用了这个解决方案(感谢 m2mdas 和http://blog.alterphp.com/2011/10/set-up-authenticationsuccesshandler.html

配置.yml

#My services
parameters:
    security.authentication.success_handler.class: MyApp\UserBundle\Resources\AuthenticationSuccessHandler

services:
    security.authentication.success_handler:
        class: %security.authentication.success_handler.class%
        public: false
        arguments:  ['@router', '@security.user.entity_manager']

安全.wml

firewalls:
    main:
        pattern: ^/
        form_login:
            provider: fos_userbundle
            csrf_provider: form.csrf_provider
            success_handler: security.authentication.success_handler
        logout:       true
        anonymous:    true

successhandler(包括比我要求的功能稍多的功能,以后可能会使用它):

<?php

namespace MyApp\UserBundle\Resources;

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Doctrine\ORM\EntityManager;


/**
 * Custom authentication success handler
 */
class AuthenticationSuccessHandler implements AuthenticationSuccessHandlerInterface
{

   private $router;
   private $em;

   /**
    * Constructor
    * @param RouterInterface   $router
    * @param EntityManager     $em
    */
   public function __construct(RouterInterface $router, EntityManager $em)
   {
      $this->router = $router;
      $this->em = $em;
   }


   function onAuthenticationSuccess(Request $request, TokenInterface $token)
   {

        if(true === $request->isXmlHttpRequest()) {
            return new Response("success");
        }

        //default redirect operation.
        $uri = $this->router->generate('MyAppSkrivbordBundle_homepage');
        return new RedirectResponse($uri);


   }
}
于 2012-12-04T11:07:08.497 回答