繁体   English   中英

身份验证后,symfony2继续执行ajax操作

[英]symfony2 go on with the ajax action after authentication

有一个使用Ajax的操作(例如,将产品添加到购物车中或只是一个类似按钮),在用户单击“添加”后,它需要查看用户是否已经登录。如果没有,请重定向到登录页面并登录,然后自动添加它并更新数据库,然后重定向到用户查看的页面。 我知道我可以在控制器中使用安全注释,但是我将如何在Ajax操作中这样做呢?

在您的控制器中:

public function ajaxAction(Request $request) {
    $authorizationChecker = $this->get('security.authorization_checker'); // Symfony 2.6+:
    //In previous Symfony versions use `security.context` service instead
    if ($authorizationChecker->isGranted('IS_AUTHENTICATED_ANONYMOUSLY')) {
        $currentUrl = $request->get('current_url');
        $request->getSession()->set('returnUrl', $currentUrl);
        return new JsonResponse('need_to_redirect');
    }
    // Do stuff that's supposed to happen when user is logged in
    return new JsonResponse('stuff_is_done');
}

在您的JavaScript中:

$.post('ajax_url', {currentUrl: window.location.href}, function(data) {
    if(data === 'need_to_redirect') {
        // redirect to login
    } else {
        // do stuff
    }
});

现在,在您的登录检查控制器中,您可以检查会话中的返回URL:

public function loginCheckAction(Request $request) {
    //after we checked that login is valid
    if($request->getSession->has('returnUrl')) {
        return new RedirectResponse($request->getSession()->get('returnUrl'));
    } else {
        return new RedirectResponse($this->generateUrl('homepage'));
    }
}

如果您正在使用Symfony的登录检查,而不是控制器操作,则必须实现自己的AuthenticationSuccessHandler

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM