I'm currently working on a inventory system with login for Admin and different units and what I need to make is the Login to redirect users deppending on their ROLE
I've read through the documentation and found loads of information but nothing I work on works.
I know the gist is to put an IF inside the onAuthenticationSuccess, and check the roles and redirect them accordingly, the problem is that I don't know how to retrieve the role after login.
I've tried checking isGranted, getRoles and the Custom APi suggestion on Symfony documentation.
Sorry if the post doesn't have the format, but I'm brand new to stackoverflow and quite new in PHP coding.
You can change the default target path for a login, see Changing the default page in the security documentation.
This will guide all your users to the same page after login. On this page you can perform a role check and display different content or redirect again based on their role. This might not be perfect - for example if you are not careful, you might get too many redirects in your browser - but it is probably the fastest and easiest way to solve your problem, because you can just use the helper methods in the Controller that you are probably more accustomed to.
If you want to already decide where to redirect your users while they login, you will need a custom Authenticator. See Step 3 in How to Build a Login Form to see how an Authenticator generally looks. You will then have to change onAuthenticationSuccess, e.g. something like this:
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
// the $token holds the user object. You might have stumbled upon this in the context of the service `security.token_storage`
$user = $token->getUser();
if (in_array('ROLE_ADMIN', $user->getRoles(), true)) {
return new RedirectResponse($this->urlGenerator->generate('app_admin_dashboard'));
}
return new RedirectResponse($this->urlGenerator->generate('default_route'));
}
Be careful that the role check I do there, might not work when you use hierarchical roles, see: Hierarchical Roles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With