Symfony2登录和安全

Fra*_*hoa 5 security login symfony

我最后一次登录时有没有办法存储?

我正在使用symfony2,一切正常,安全配置正常.

我已经看到这个安全性并登录基于Symfony 2的项目,这是一个类似的问题,但它不符合我的需求.

还有其他解决方案吗?

eag*_*tor 15

您可以创建一个AuthenticationHandlerSymfony将在用户成功登录时调用,您可以将登录时间保存到User实体属性中(假设您有此方案).

首先,创建成功身份验证处理程序:

namespace Acme\TestBundle\Handler;

use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\DependencyInjection\ContainerAware;

class AuthenticationHandler extends ContainerAware implements AuthenticationSuccessHandlerInterface
{
    function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        $token->getUser()->setLoginTime(new \DateTime());
        $this->container->get('doctrine')->getEntityManager()->flush();

        return new RedirectResponse($this->container->get('router')->generate('login_success'));
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您需要将身份验证处理程序注册为配置文件中的服务,例如, src/Acme/TestBundle/resources/Config/services.yml

services:
    authentication_handler:
        class: Acme\TestBundle\Handler\AuthenticationHandler
        calls:
            - [ setContainer, [ @service_container ] ] 
Run Code Online (Sandbox Code Playgroud)

并配置登录表单以使用创建的处理程序,检查您的 security.yml

form_login:
    success_handler: authentication_handler
Run Code Online (Sandbox Code Playgroud)

显然,要使其工作,您需要拥有一个User具有loginTime属性的实体和相应的setter.您需要配置登录以使用User实体存储库作为用户提供程序DaoAuthenticationProvider,如下所述:http://symfony.com/doc/current/book/security.html#loading-users-from-the-database.


Seb*_*oFr 5

一个非常简单的解决方案是在您的应用程序中实现FOSUserBundle,因为数据库中的每个用户条目都包含(其中包括)"last_login"字段.