How to create custom Remember me provider in symfony

时间:2016-04-04 17:19:38

标签: php symfony cookies authorization remember-me

I will explain my problem. I am logging in users using an API passing username and encrypted password, so I am unable to load users only by username.

I am using GUARD to get the user details and authorize the users for a given firewall. So far so good.

My problem begins when I wan to activate the remember me. Obviously as the user is not stored in my database, the remember me fails to load the user by name.

At the moment I overcome the issue implementing the class RememberMeServicesInterface and using my new class in my guard class that extends AbstractFormLoginAuthenticator.

To be honest to me it feels like an hack as I am pretty much sure there must be a better way to do this.

Checking the code I have noticed that Symfony has 2 classes that implement RememberMeServiceInterface, TokenBasedRememberMeServices and PersistentTokenBasedRememberMeServices, can someone explain me how could I inject also my RememberMeService and use that to authorize my user?

Thanks in advance to the community for the help.

1 个答案:

答案 0 :(得分:7)

我终于找到了一种方法来实现自定义记住我。 这些是步骤:

1)创建一个扩展Symfony \ Bundle \ SecurityBundle \ DependencyInjection \ Security \ Factory \ RememberMeFactory

的类

此类使用自定义键和create()覆盖getKey(),以便我可以注入自己的令牌服务security.authentication.rememberme.services.MYCUSTOMTOKENSERVICE

2)创建一个扩展Symfony \ Component \ Security \ Http \ RememberMe \ TokenBasedRememberMeServices的令牌服务,以便我可以使用我的身份验证逻辑和我的自定义UserProvider函数

3)创建一个扩展Symfony \ Component \ Security \ Http \ RememberMe \ ResponseListener的侦听器

4)在我的服务yml文件中绑定

customlistener.security.authentication.listener:           class:#####           public:false

security.authentication.rememberme.services.customtokenservice:           class:###           parent:" security.authentication.rememberme.services.abstract"           abstract:true

5)在security.yml中,我使用我在getKey中使用的字符串来回忆我的监听器custom-remember-me,使用相同的remember-me键选项

像魅力一样工作!