Symfony2登录和安全性 [英] Symfony2 Login and Security
问题描述
有没有一种方法可以存储用户上次登录的时间?
Is there a way I can store when was the last time a user logged in?
我正在使用symfony2,并且在安全配置下一切正常.
I'm using symfony2, and everything's working alright with the security configuration.
我已经看到了这个安全性并在Symfony上登录基于2的项目,这是一个类似的问题,但是它根本不符合我的需求.
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会调用的AuthenticationHandler
,您可以将登录时间保存到User
实体属性中(假设您有这种情况).
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).
首先,创建成功身份验证处理程序:
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'));
}
}
然后,您需要在配置文件(例如,src/Acme/TestBundle/resources/Config/services.yml
Then you need to register the authentication handler as a service in a configuration file, for example, src/Acme/TestBundle/resources/Config/services.yml
services:
authentication_handler:
class: Acme\TestBundle\Handler\AuthenticationHandler
calls:
- [ setContainer, [ @service_container ] ]
并配置登录表单以使用创建的处理程序,签出您的security.yml
And configure the login form to use the created handler, check out your security.yml
form_login:
success_handler: authentication_handler
很明显,要使其正常工作,您需要具有一个带有loginTime
属性和相应设置器的User
实体.并且您需要配置登录名以使用User
实体存储库作为用户提供者,并使用DaoAuthenticationProvider
,如此处所述:
Obviously, for this to work, you need to have a User
entity with a loginTime
property and the corresponding 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.
这篇关于Symfony2登录和安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!