简体   繁体   English

Symfony2登录和安全

[英]Symfony2 Login and Security

Is there a way I can store when was the last time a user logged in? 我最后一次登录时有没有办法存储?

I'm using symfony2, and everything's working alright with the security configuration. 我正在使用symfony2,一切正常,安全配置正常。

I've seen this Security and login on a Symfony 2 based project , which is a similar question, but it just doesn't fit my needs. 我已经看到这个安全性并登录基于Symfony 2的项目 ,这是一个类似的问题,但它不符合我的需求。

Is there any other solution? 还有其他解决方案吗?

You can create an AuthenticationHandler that Symfony will call when user login successfully, you can save the login time into a User entity property (supposing that you have this scenario). 您可以创建一个Symfony将在用户成功登录时调用的AuthenticationHandler ,您可以将登录时间保存到User实体属性中(假设您有此方案)。

First, create the success authentication handler: 首先,创建成功身份验证处理程序:

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'));
    }
}

Then you need to register the authentication handler as a service in a configuration file, for example, src/Acme/TestBundle/resources/Config/services.yml 然后,您需要将身份验证处理程序注册为配置文件中的服务,例如, src/Acme/TestBundle/resources/Config/services.yml

services:
    authentication_handler:
        class: Acme\TestBundle\Handler\AuthenticationHandler
        calls:
            - [ setContainer, [ @service_container ] ] 

And configure the login form to use the created handler, check out your security.yml 并配置登录表单以使用创建的处理程序,检查您的security.yml

form_login:
    success_handler: authentication_handler

Obviously, for this to work, you need to have a User entity with a loginTime property and the corresponding setter. 显然,要使其工作,您需要具有loginTime属性的User实体和相应的setter。 And you need to configure the login to use the User entity repository as user provider and the DaoAuthenticationProvider , as explained here: http://symfony.com/doc/current/book/security.html#loading-users-from-the-database . 您需要配置登录以使用User实体存储库作为用户提供程序和DaoAuthenticationProvider ,如下所述: http//symfony.com/doc/current/book/security.html#loading-users-from-the-数据库

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

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

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