>

Course Overview

Login to bookmark this course

FOSUserBundle FTW! (v1.3)

Unlock superior security with Symfony's FOSUserBundle. Our tutorial makes installation and configuration a breezy affair!

  • 186 students
  • EN Captions
  • EN Script
  • Certificate of Completion

Your Guides

About this course

Learn to install, configure, and master the most important parts of FOSUserBundle in this screencast.

FOSUserBundle is the most popular Symfony bundle, and with good reason. It comes packed with features for login, registration, forgot password and a lot more. But it's also a big tool, and learning to master it will go a long way to making the security system in your application great.

72 Comments

Sort By
Login or Register to join the conversation
Default user avatar Hugo Hamon 6 years ago

Nice tutorial! UserBundle looks easier to use.

5 | Reply |
Default user avatar Niel Shine 6 years ago

HI

Can you update this tutorial please ?

2 | Reply |

Hi Niel!

I *really* want to - but I can't until FOSUserBundle finally tags their 2.0 release (otherwise we risk making a tutorial and then having them change a lot of stuff before that stable version). As soon as that happens, we'll be on it!

2 | Reply |

Ryan,

Any chance of maybe some source code that you could point to that uses Guard along with FOS_UserBundle? I feel like I am so close to making this work, but am missing something. :-(

| Reply |

Hey Jon!

I just checked, I don't have any handy right now :/. But, what problem are you running into?

| Reply |

Finally, they tagged the 2.0 release of the bundle. Tutorial updated! https://knpuniversity.com/s...

| Reply |

Hi Ryan,

can we use FOSUserBundle also for Symfony3.x too?

Thanks for the information
Teo

1 | Reply |

Hey Teo!

Absolutely! However, FOSUserBundle version 2.0 is not QUITE released yet (it's BETA 1 at this moment), and you'll need to use this new version in Symfony 3. Their documentation tells you how to install this beta version of the bundle: https://symfony.com/doc/mas.... It's basically stable, and I expect a release VERY soon - we're just waiting for one last issue to be resolved. Btw, once they release that bundle, we're going to totally update this tutorial (woohoo!).

Cheers!

1 | Reply |
Default user avatar Mojo Jojo 6 years ago

Leanna is such a wonderful and lucid instructor that it makes understanding of complex topics so much easier. I don't think I'd have grasped Symfony2 the way I had, had it not been for Leanna's instructional videos. Thumbs up for the effort.

1 | Reply |
Default user avatar Aman Varshney 6 years ago

Awesum tutorial....big thanks for this tutorial..

| Reply |
Default user avatar Paca-vaca 6 years ago

Really good work. Thank you.

| Reply |
Default user avatar Richa Kalangutker 6 years ago

hi... i need some help in adding new fields to FOSUserBundle.. I followed the tutorial on https://github.com/FriendsO... but i get an error saying Neither element "fname" nor method "setFname()" exists in class "Acme\UserBundle\Entity\User" where Fname is my new field...
Please help me!!!!

Thanks

| Reply |
Default user avatar bbmatt1 6 years ago

Great tutorial - just one thing, the encoders entry is removed in the tutorial, but the default FOS from the documentation one isn't added, so when you use the console to add a user, it throws up an encoding error.

| Reply |
Default user avatar Mohammed Ezz El-Din Eisa 6 years ago

Thanks . Life is cool with FOS !!

| Reply |
Default user avatar Zorg-iris 6 years ago

thank look and work great, but i have question is the resetting work ?

| Reply |
Default user avatar Никита Сапогов 6 years ago

Thanks for tutorial

| Reply |
Default user avatar radovan 6 years ago

I have not the deps document in symfony2.1.6

| Reply |

Yes, that's one of the areas where this video is out of date. Starting with Symfony 2.1, using the composer.json file. Follow along with the official docs to see what you'll need :).

Thanks!

| Reply |
Default user avatar Matteo Poile 6 years ago

Thank you very much!

| Reply |
Default user avatar Robert Speer 6 years ago

How upto date is this video? There appear to be some significant differences between what's in this tutorial and what's in the instructions on GitHub: https://github.com/FriendsO...

| Reply |

Answer, pretty close but keep an eye on the github doc's

| Reply |

This entry is indeed a bit out of date - you can use it for big picture stuff, but as Robert says, watch the real docs! We'll hopefully update this at some point, just a matter of finding some time :).

| Reply |

i would love to see a more updated version of this. the video takes some of the intimidation out of the bundle :]

2 | Reply |
Default user avatar bassemreda 6 years ago

Thanks so much for this tutorial.

| Reply |
Default user avatar We Burn It TV 6 years ago

Big thanks Leanna!

| Reply |
Default user avatar webornot 6 years ago

Nice job !

| Reply |
Default user avatar Sergey Zherevchuk 6 years ago

It was awesome! Thx!

| Reply |
Default user avatar Hihi Hehe Ặc Ặc 6 years ago

Nice tutorial series :)

| Reply |

Nice work guys, this is great!

| Reply |
Default user avatar anton 6 years ago

Thanks for clear tutorial!

| Reply |

At first
thank you very much Really you are very helpful

seconed

i
have install fosuserbundle on my project and it is working well but
when i acess the login form it redirect me to the symfony login form in
demobundle after i remove the demobundel it give me now
The controller for URI "/login" is not callable.
although i configured the main firewall as fos provider but it does'nt work

any suggestion ?

| Reply |

Hi, great tutorial!

I would like to know what's better to use for user's login/registration, using this bundle or the one we made in "Starting in Symfony2: Episode 2"

| Reply |

I'm mixed. FOSUserBundle is much faster to start, and you get a lot of features out of the box. But eventually, you will need to override more and more, and you lose the initial benefit. The answer depends on the comfort-level of the developer to do what we did in Episode 2 and how big the project will be.

Cheers!

2 | Reply |
Default user avatar Patrick 6 years ago

Hey guys, i got a problem with the FosUserBundle.

I know how to add new fields to the registration form (OneToOne relationed fields).

But when i try to add an Address form type to the registration formular by using the FOsUserBundle Registration Controller,

i don't know how to pass the "empty" Address Object to the User in the Registration Controller so that the fields are displayed and later map the address to the user. (User - Address = OneToMany relation)

Is overwriting the RegistrationFormHandler to the following the correct solution. It is working fine, but maybe there is another way:

public function process($confirmation = false)
{
$user = $this->createUser();
$user->addAddress(new Address());

$this->form->setData($user);

// ...
}
I hope you can help me, ur the best!
Regards.

| Reply |

Hey Patrick!

Yes, overriding the RegistrationFormHandler seems just fine to me! There's not really a *best* way to do this - there are some options, and whichever works easiest is just fine. For example, you might (never tried on a collection) be able to use the empty_data option (http://symfony.com/doc/curr... on the `addresses` field when setting up your form to be an array with a single Address entity on it. You *could* also add 1 Address to each User in the User's __construct() function (though you'd then need to cascade persist and need to be ok with a potentially "empty" Address record being saved in the database.

So, as you can see, I like your solution just fine :).

Cheers!

| Reply |

Ok, thanks for checking that ryan :) !
At first, i did it like you mentioned in the Constructor, but always adding an empty address to a user whenever one is created did not seem legit for me :D.
Oh yeah Ryan before i forget to ask: Do you know something about the "remember_me" feature on localhost development with FosUserBundle , that it is broken ? Because when i logout, Chrome does not delete the Cookie but Firefox does. I thought, that it might be a problem on localhost development (xampp).

| Reply |

Hi weaverryan,

Nice tuts btw, I was hoping you could lead me to the right direction as I am having issues with overriding the ProfileController, in particular the editAction. This is what I want to achieve, an admin can update the profile of any user.

What I have done so far.

1. Created a list of users with an edit link (mydomain/admin/user/5/edit).
2. Created my own bundle and defined FOSUserBundle as its parent.
3. Copied the ProfileController in my controller folder and removed everything except for the use statements and editAction.

Issues:

Scenario: I'm logged-in as admin

1. When updating other user - not saving $form->isValid() returns false and $form->submitted is false
2. When updating my own profile - It saves but throwing error
Controller "mypath\COntroller\ProfileController::showACtion" for URI /profile/ is not callable

Please see my code below. Thanks in advance!

/**
* Edit the user
*/

public function editAction(Request $request)
{

// Get current user.
$user = $this->container->get('security.context')->getToken()->getUser();

// Get target user.
$target_user_post = $request->request->get('smd_user_profile');
$user_manager = $this->container->get('fos_user.user_manager');
$target_user = $user_manager->findUserByEmail($target_user_post['email']);

if($target_user) // detect if the edit_users form sent the request rather than self-updating
{
$target_user->setName($target_user_post['name']);
} else {
$target_user = $user;
}

if (!is_object($target_user) || !$target_user instanceof UserInterface) {

throw new AccessDeniedException('This user does not have access to this section.');

}

/** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */

$dispatcher = $this->get('event_dispatcher');

$event = new GetResponseUserEvent($target_user, $request);

$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_INITIALIZE, $event);

if (null !== $event->getResponse()) {

return $event->getResponse();

}

/** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */

$formFactory = $this->get('fos_user.profile.form.factory');

$form = $formFactory->createForm();

$form->setData($target_user);

$form->handleRequest($request);

if ($form->isValid()) {

/** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */

$userManager = $this->get('fos_user.user_manager');

$event = new FormEvent($form, $request);

$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);

$userManager->updateUser($target_user);

if (null === $response = $event->getResponse()) {

$url = $this->generateUrl('fos_user_profile_show');

$response = new RedirectResponse($url);

}

$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_COMPLETED, new FilterUserResponseEvent($target_user, $request, $response));

return $response;

}

return $this->render('FOSUserBundle:Profile:edit.html.twig', array(

'form' => $form->createView()

));
}
}

| Reply |

Hi Mel!

Hmm, so for your 2 issues:

1) I'm not sure why the form would show as non-submitted. My advice would be to *not* try to re-use the ProfileController for FOSUserBundle for this - that's really meant for a user to edit their *own* profile. If you have a screen where you're editing other people's profiles, just create a new route/controller for this and setup it up manually - that will be much more naturla.

2) About the "is not callable" error, this tells me that somewhere, you have a route setup for /profile/. You should be able to see this if you run "php app/console router:match /profile/". The error means that the _controller value is not pointing to a valid function. Usually, this means that it finds your controller class, but does *not* find the method inside that class. So, reading directly from your error, it means that it doesn't find a 'showAction' inside of that ProfileController class.

Good luck!

| Reply |

I see, I will try and implement this feature manually.

Thanks for the reply.

| Reply |
Default user avatar Sudhir Gupta 6 years ago edited

hi there ,
in FOSUserbundle, i want to change the way of login. instead of traditional login (hit submit and page redirect) i want to use ajax login.
so in order to achieve this, i make a JavaScript. my code is handling request perfectly but problem is that i am not able to fetch the details that credentials (login true or false).

Here i am getting all HTML code of redirected page. (in my case, its redirecting /admin page and i am getting view sources in console.)
as per my UI, i want to show that like "user validated..you will redirect in a moment "

So, may u help me that how i can achieve this target.

Here is my js code.


var resp ="";
$(document).ready(function(){
    $('#_submit').click(function(e){

        e.preventDefault();
        resp = ajaxLogin($(this).attr('path'));
        /* add ajax code here to check validation */
        if(resp==1) {
            setTimeout(function () {
                $(that).addClass("success");
                setTimeout(function () {
                    $app.show();
                    $app.css("top");
                    $app.addClass("active");
                }, submitPhase2 - 70);
                setTimeout(function () {
                    $login.hide();
                    $login.addClass("inactive");
                    animating = false;
                    $(that).removeClass("success processing");
                }, submitPhase2);
            }, submitPhase1);
        }
        else{
            alert(resp);
            console.log(resp);
        }

    });
});

| Reply |

Hey, Sudhir!

Ah, yes, I know exactly what you mean! It's already an expert level. :)

You need to create your custom failure and success handlers which will return a JsonResponse on each Ajax auth request. They should be declare in the security.yml as:

security:
    firewalls:
        main:
            form_login:
                failure_handler: your_custom_auth_failure_handler
                success_handler: your_custom_auth_success_handler

For example, in you custom success auth handle you need to return a JsonResponse if you see an XmlHttpRequest:

class CustomAuthenticationSuccessHandler extends DefaultAuthenticationSuccessHandler
{
    public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        if ($request->isXmlHttpRequest()) {
            return new JsonResponse([
                'authenticated' => true,
                'id' => $token->getUser()->getId(),
            ]);
        }

        return parent::onAuthenticationSuccess($request, $token);
    }
}

And similar changes for failure auth handle, but this time you need to extend "DefaultAuthenticationFailureHandler" class, where you just return JsonResponse if you got a XmlHttpRequest.

Cheers!

| Reply |
Default user avatar Sudhir Gupta Victor 6 years ago edited

thank you victor

but pls help me with file name and location that where i have to write class CustomAuthenticationSuccessHandler
and in ajax i have to change landing path or it will be same as 'login_check'

| Reply |

No, it should be still "/login_check"! Actually, it should be a value of "check_path" config key in security.yml (http://symfony.com/doc/current/reference/configuration/security.html#check-path ).

You can place these handlers whenever you want. But you need to declare them as a service. Actually, "your_custom_auth_failure_handler" and "your_custom_auth_success_handler" names in my previous comment are the services names. For example, place your classes under "AppBundle\Security\Http\Authentication" namespace to be consistent with "DefaultAuthenticationSuccessHandler" class which you extend. Here's an example of service declaration:


    your_custom_auth_failure_handler:
        class: AppBundle\Security\Http\Authentication\CustomAuthenticationFailureHandler
        arguments:
            - "@http_kernel"
            - "@security.http_utils"

    your_custom_auth_success_handler:
        class: AppBundle\Security\Http\Authentication\CustomAuthenticationSuccessHandler
        arguments:
            - "@security.http_utils"

Cheers!

| Reply |
Default user avatar ciudadano82 Victor 6 years ago

Hi Victor! Is there any documentation / tutorials related to those handlers (DefaultAuthenticationSuccessHandler and DefaultAuthenticationFailureHandler)?

| Reply |

Hey ciudadano82 ,

Actually, these cases covered with the new Guard component. Check out the onAuthenticationSuccess() and onAuthenticationFailure() methods there.

Also we have a course about Guard: KnpUGuard: Symfony Authentication with a Smile. You also can check out Symfony Security: Beautiful Authentication, Powerful Authorization Symfony course based on Guard component.

Cheers!

| Reply |
Default user avatar Hakim Ch 6 years ago

I a have a problem with routing :(
My main routes use anotation and for pages @Route("/{pageSlug}", name="otherpage")
and when i want access to the /register or any fos page it redirect me the my main route

| Reply |

Hey Hakim,

Are you logged in? I think you can't register when you're already logged in. Also, double check your access_control configuration in the security.yml with this docs: https://symfony.com/doc/mas... - maybe /register page just behind the firewall.

Cheers!

| Reply |

When i desactivate my main route the register work... :(

I found a solution but i dont know if it resolve totaly my issue is by excluding register in the the requirement in my main route

| Reply |

Hm, it's weird. I'd suggest you look over the usage of your main route. Probably you pointed it somewhere in config files or redirect to it in an event listener. But if so, you probably get an 500 error when you deactivate it. Also don't forget to clear the cache, sometimes Symfony doesn't regenerate it when you work with annotations.

Cheers!

| Reply |
Default user avatar Laila M. 6 years ago

Please an update for FosUserBundle with Symfony4, specially for controller overriding.

| Reply |

Delete comment?

Share this comment

astronaut with balloons in space

"Houston: no signs of life"
Start the conversation!