Symfony2 + MongoDB for user managment
I’ve been playing with Symfony2 and MongoDB last few days and got to a situation that I want to use MongoDB for user managment.
This turned out to be a bit undocumented on the interwebs.
Looking for “symfony2 mongodb user authentication” I found:
Using mongodb for user authentication in symfony 2.1 which just confused me…
mongodb symfony user authentication? which resolved to using FOSUserBundle, not too great for learning how to do stuff.
Custom MongoDB Security Provider in Symfony2 which gave some really good points, and combined with this awesometacular comment gave a very good base for doing da work.
I presume you know some basics, as creating your own bundle and similar.
Fiiiiiiiiiiiiiiiiiiirst, register custom security provider for providing users:
in app/config/security.yml
Second, register service. As per this great comment by Stof
DoctrineMongoDBBundle provides a DocumentUserProvider for Mongo making it easy to use a Mongo provider when you don’t need the features of FOSUserBundle. The only need is to register a service using it
(Stof I luv U)
in src/Spoygg/ProfajlerBundle/Resources/config/services.yml
“arguments” in this code snippet are:
- @doctrine.odm.mongodb.document_manager – “DoctrineMongoDBBundle provides a DocumentUserProvider for Mongo” that Stof mentioned
- SpoyggProfajlerBundle:Profileuser – model for users, MongoDB document declared in my bundle src/Spoygg/ProfajlerBundle/Document/Profileuser.php
- username – field of your user class that will be used to retrieve user by username
Third, declare your user model, it needs to implement Symfony\Component\Security\Core\User\UserInterface. I’ll leave that to you, no code for you lazy copy-pasters out there. Just know that it must be a class that you passed as a second argument in previous code snippet.
Fourth, once more in app/config/security.yml, this time we will declare encoder for our user model.
That is all! One of those stuff that is really, really simple when you know how.
Some points to take care of:
- read Stof’s comment, it has some good stuff to notice
- great implementation of UserInterface by FOS you can use to as a role model to create your stuff
- you need to use DoctrineMongoDBBundle
- you need to know how to setup the rest of security.yml
- I did not bother with real tough security best practices. You will need to concern yourself with properly securing your app!!! (read next point)
- I have intentionally left out everything that does not have direct impact on this task, you will have to fill in the holes, if you do not know how: Why you even try to implement user auth with MongoDB in Symfony2?
UPDATE:
just found this neato little post that basically says the same as I ventured above but has a XML flavour.