fosuserbundle在ovveriding loginaction上获取错误消息

时间:2014-01-18 12:33:02

标签: symfony fosuserbundle

我使用:

覆盖loginaction
namespace PjDZ\UserBundle\Controller;

use FOS\UserBundle\Controller\SecurityController as BaseController;
use Symfony\Component\HttpFoundation\RedirectResponse;

class SecurityController extends BaseController {
    public function loginAction(\Symfony\Component\HttpFoundation\Request $request)
    {
         $response   = parent::loginAction($request);

        //how can i get error message if exist from $response ??

        return $response;
    }
}

我希望得到主loginaction中生成的错误消息。 谢谢,抱歉我的英语不好。

1 个答案:

答案 0 :(得分:2)

错误消息存在于请求或会话中。如果您想访问它,只需复制SecurityController

中的代码即可
namespace PjDZ\UserBundle\Controller;

use FOS\UserBundle\Controller\SecurityController as BaseController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\SecurityContext;

class SecurityController extends BaseController
{
    public function loginAction(\Symfony\Component\HttpFoundation\Request $request)
    {
        /** @var $session \Symfony\Component\HttpFoundation\Session\Session */
        $session = $request->getSession();

        // get the error if any
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
        } elseif (null !== $session && $session->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
        } else {
            $error = '';
        }

        if ($error) {
            $error = $error->getMessage();
        }

        // do something with the $error message!

        return parent::loginAction($request);;
    }
}

小心,我删除了$session->remove()部分,因此父操作也能够从会话中获取错误消息。