Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create custom Remember me provider in symfony

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.

like image 749
soipo Avatar asked Dec 06 '25 14:12

soipo


1 Answers

I have finally found a way to achieve custom remember me. These are the steps:

1) Create a class that extends Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\RememberMeFactory

This class overrides getKey() with a custom key and create() so I can inject my own token service security.authentication.rememberme.services.MYCUSTOMTOKENSERVICE

2) Create a token service that extends Symfony\Component\Security\Http\RememberMe\TokenBasedRememberMeServices so that I could use my authentication logic and my custom UserProvider function

3)Create a listener that extends Symfony\Component\Security\Http\RememberMe\ResponseListener

4)Bind together in my service yml file

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

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

5) In security.yml I use the string I used in getKey to recall my listener custom-remember-me with same options of remember-me key

Worked like a charm !

like image 189
soipo Avatar answered Dec 08 '25 04:12

soipo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!