It's possibile with security file config to redirect user already logged in to specific route (e.g homepage) if they try to access on login/register pages? One solution that I already found is to attach a listener to EventRequest, but I prefer to use security config if it's possible.
After some googling I noticed that another solution is to override the fosuserbundle controllers. But because I need that this behavior should works also for /register and /resetting pages, instead to override also those controller, I preferred to use EventListener. Maybe this's the best solution in this case. I'm using Symfony 4, so for the other versions could be different.
My code:
namespace App\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
class LoggedInUserListener
{
private $router;
private $authChecker;
public function __construct(RouterInterface $router, AuthorizationCheckerInterface $authChecker)
{
$this->router = $router;
$this->authChecker = $authChecker;
}
/**
* Redirect user to homepage if tryes to access in anonymously path
* #param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$path = $request->getPathInfo();
if ($this->authChecker->isGranted('IS_AUTHENTICATED_REMEMBERED') && $this->isAnonymouslyPath($path)) {
$response = new RedirectResponse($this->router->generate('homepage'));
$event->setResponse($response);
}
}
/**
* Check if $path is an anonymously path
* #param string $path
* #return bool
*/
private function isAnonymouslyPath(string $path): bool
{
return preg_match('/\/login|\/register|\/resetting/', $path) ? true : false;
}
}
add this to services.yaml:
App\EventListener\LoggedInUserListener:
tags:
- { name: kernel.event_listener, event: kernel.request }
#Mintendo, I have errors using your code:
request.CRITICAL: Exception thrown when handling an exception (Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException: The token storage contains no authentication token.
php.CRITICAL: Uncaught Exception: The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL.
Besides that debug bar also showed error and was broken.
But you pushed me in the right direction, so I have modified your code a little.
And it works without errors now:
<?php
namespace App\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Security;
class LoggedInUserListener
{
private $router;
private $security;
public function __construct(RouterInterface $router, Security $security)
{
$this->router = $router;
$this->security = $security;
}
/**
* Redirect user to homepage if tries to access in anonymously path
* #param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$path = $request->getPathInfo();
if ($this->security->getUser() && $this->isAnonymouslyPath($path)) {
$response = new RedirectResponse($this->router->generate('dashboard'));
$event->setResponse($response);
}
}
/**
* Check if $path is an anonymously path
* #param string $path
* #return bool
*/
private function isAnonymouslyPath(string $path): bool
{
return preg_match('/\/login|\/register|\/resetting/', $path) ? true : false;
}
}
Related
Good morning to all
Please i need help. I am using JWT Authentication and all works well.But my problem is to retreive the current user after the login. I saw in the documentation that i can create a controller to do so, but after doing that i get the error of id parameter not given.
Here is my controller related to the user entity
// api/src/Controller/GetMeAction.php
namespace App\Controller;
use App\Entity\User;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
class GetMeAction
{
/**
* #param Security
*/
private $_security;
public function __construct(Security $security)
{
$this->_security = $security;
}
/**
* #Route(
* name="get_me",
* path="get/me",
* methods={"GET"},
* defaults={
* "_api_resource_class"=User::class,
* "_api_item_operation_name"="get_me"
* }
* )
*/
public function __invoke(Request $request): User
{
return $this->_security->getUser();
}
}
Im using symfony 5.3, i wanted to use the api platform normalization and the item operation "get" to keep all the custom config, security, services, ...
So I used the forward() method in a controller :
/**
* #Route("/api/user/me", name="get_me")
*/
public function getMe(): Response
{
$router = $this->get('router')->getRouteCollection()->get('api_users_get_item');
$defaults = $router->getDefaults();
return $this->forward($router->getDefault('_controller'), array_merge($defaults, [ 'id' => $this->getUser()->getId()]));
}
Previous answer is right, but you forgot to Extend you controller from abstract one:
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class AdminController extends AbstractController
{
}
If you want to get User in the service, you can Inject Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface in your __construct()
and you can get user like:
public function getUser(): ?User
{
$token = $this->tokenStorage->getToken();
if (!$token) {
return null;
}
$user = $token->getUser();
if (!$user instanceof User) {
return null;
}
return $user;
}
i am developing a symfony restful api with tools like
FosRestBundle, FosUserBundle and Lexik JWT for api authentication.
I need to save each successful login in my app. So i created a Login entity
(user_id,loginDate) , but i don't know how to use it because the login in handled from Lexik.
Does anyone know how can i do this?
Thanks
You can use security.interactive_login event for that. More information can be found from the official documentation:
https://symfony.com/doc/current/components/security/authentication.html#authentication-events
Create the listener and register it:
namespace App\EventListener;
use App\Component\EntityManagerAwareTrait;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
/**
* #package App\EventListener
*/
class SecuritySubscriber implements EventSubscriberInterface
{
/**
* #param EntityManagerInterface $em
*/
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
/**
* #return array
*/
public static function getSubscribedEvents(): array
{
return [
SecurityEvents::INTERACTIVE_LOGIN => 'onSecurityInteractiveLogin',
];
}
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event): void
{
$user = $event->getAuthenticationToken()->getUser();
if ($user instanceof User) {
$user->setLoginDate(new \DateTime());
$this->em->persist($user);
$this->em->flush();
}
}
}
I have a single Symfony website which has 2 domains:
landing (www.landing.com)
main domain (www.main.com
I should configure it so that every request which matches the landing host (www.landing.com) redirects to the homepage. Requests on the main domain should work as usual.
Is it possible? I tried with this but it redirects only the homepage:
/**
* #Route("/", name="landing", host="www.landing.com")
*/
public function landingAction()
{
return $this->render('default/landing.html.twig');
}
/**
* #Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
return $this->render('default/index.html.twig');
}
I ended up using a listener and check the host of the current page. This way I can even parameterize the host.
This is the complete code:
<?php
namespace AppBundle\EventListener;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
class LandingListener
{
private $landingPageHost;
private $router;
public function __construct($landingPageHost, $router)
{
$this->landingPageHost = $landingPageHost;
$this->router = $router;
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$host = $request->getHost();
$isHomepage = 'homepage' == $request->attributes->get('_route');
// landing page domain
if (false !== stripos($host, $this->landingPageHost) && !$isHomepage) {
$url = $this->router->generate('homepage');
$response = new RedirectResponse($url);
$event->setResponse($response);
}
}
}
This is the service:
app.landing_listener:
class: AppBundle\EventListener\LandingListener
arguments: ['%landing_page_host%', '#router']
tags:
- { name: kernel.event_listener, event: kernel.request }
You could forward the request of www.landing.com to homepage route.
Tested in Symfony 3.3
Though not very common, you can also forward to another controller internally with the forward() method. Instead of redirecting the user's browser, this makes an "internal" sub-request and calls the defined controller.
The forward() method returns the Response object that is returned from that controller, just change the host with theirs:
/**
* #Route("/", name="landing", host="localhost")
*/
public function landingAction()
{
// return $this->render('default/landing.html.twig');
$response = $this->forward('AppBundle:Default:index');
//further modify the response or return it directly
return $response;
}
/**
* #Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
return $this->render('default/index.html.twig');
}
Even , you can pass arguments to the resulting controller:
$response = $this->forward('AppBundle:Something:fancy', array(
'name' => $name,
'color' => 'green',
))
Reference: https://symfony.com/doc/3.3/controller/forwarding.html
Question: How to get the form_login.check_path by given firewall name?
We subscribe to Symfony\Component\Security\Http\SecurityEvent::INTERACTIVE_LOGIN in order to log successful logins inside an Application that has multiple firewalls.
One firewall uses JWT tokens via Guard authentication which has the negative effect that this event is triggered for every request with a valid token.
We have currently solved this by manually checking whether the current route matches the firewall's check-path and stopping the event-propagation together with an early return otherwise.
As we're adding more firewalls (with different tokens) I'd like to solve this more generally. Therefore I want to check whether the current route matches the current firewalls check-path without hardcoding any route or firewall-name.
There is a class to generate Logout URLs for the current firewall used by Twig logout_path() method which gets the logout route/path from the firewall listeners somehow. (Symfony\Component\Security\Http\Logout\LogoutUrlGenerator)
Before I hop into a long debugging session I thought maybe someone has solved this case before ;)
Any ideas?
Example code:
class UserEventSubscriber implements EventSubscriberInterface
{
/** #var LoggerInterface */
protected $logger;
/** #var FirewallMapInterface|FirewallMap */
protected $firewallMap;
public function __construct(LoggerInterface $logger, FirewallMapInterface $firewallMap)
{
$this->logger = $logger;
$this->firewallMap = $firewallMap;
}
public function onInteractiveLogin(InteractiveLoginEvent $event)
{
$request = $event->getRequest();
$firewallName = $this->firewallMap->getFirewallConfig($request)->getName();
$routeName = $request->get('_route');
if (('firewall_jwt' === $firewallName) && ('firewall_jwt_login_check' !== $routeName)) {
$event->stopPropagation();
return;
}
$this->logger->info(
'A User has logged in interactively.',
array(
'event' => SecurityEvents::INTERACTIVE_LOGIN,
'user' => $event->getAuthenticationToken()->getUser()->getUuid(),
));
The check_path option is only available from authentication factory/listener, so you could pass this configuration manually to the subscriber class while the container is building.
This solution take account that check_path could be a route name or path, that's why HttpUtils service is injected too:
namespace AppBundle\Subscriber;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\FirewallMapInterface;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\Security\Http\SecurityEvents;
class UserEventSubscriber implements EventSubscriberInterface
{
private $logger;
private $httpUtils;
private $firewallMap;
private $checkPathsPerFirewall;
public function __construct(LoggerInterface $logger, HttpUtils $httpUtils, FirewallMapInterface $firewallMap, array $checkPathsPerFirewall)
{
$this->logger = $logger;
$this->httpUtils = $httpUtils;
$this->firewallMap = $firewallMap;
$this->checkPathsPerFirewall = $checkPathsPerFirewall;
}
public function onInteractiveLogin(InteractiveLoginEvent $event)
{
$request = $event->getRequest();
$firewallName = $this->firewallMap->getFirewallConfig($request)->getName();
$checkPath = $this->checkPathsPerFirewall[$firewallName];
if (!$this->httpUtils->checkRequestPath($request, $checkPath)) {
$event->stopPropagation();
return;
}
$this->logger->info('A User has logged in interactively.', array(
'event' => SecurityEvents::INTERACTIVE_LOGIN,
'user' => $event->getAuthenticationToken()->getUser()->getUsername(),
));
}
public static function getSubscribedEvents()
{
return [SecurityEvents::INTERACTIVE_LOGIN => 'onInteractiveLogin'];
}
}
After regiter this subscriber as service (AppBundle\Subscriber\UserEventSubscriber) we need implement PrependExtensionInterface in your DI extension to be able to access the security configuration and complete the subscriber definition with the check paths per firewall:
namespace AppBundle\DependencyInjection;
use AppBundle\Subscriber\UserEventSubscriber;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
class AppExtension extends Extension implements PrependExtensionInterface
{
// ...
public function prepend(ContainerBuilder $container)
{
$checkPathsPerFirewall = [];
$securityConfig = $container->getExtensionConfig('security');
foreach ($securityConfig[0]['firewalls'] as $name => $config) {
if (isset($config['security']) && false === $config['security']) {
continue; // skip firewalls without security
}
$checkPathsPerFirewall[$name] = isset($config['form_login']['check_path'])
? $config['form_login']['check_path']
: '/login_check'; // default one in Symfony
}
$subscriber = $container->getDefinition(UserEventSubscriber::class);
$subscriber->setArgument(3, $checkPathsPerFirewall);
}
}
I hope it fits your need.
for PHP8
In __construct :
public function __construct(
private RequestStack $requestStack,
private FirewallMapInterface $firewallMap
)
{
}
use this :
$firewallName = $this->firewallMap->getFirewallConfig($this->requestStack->getCurrentRequest())->getName();
I use the sonata-admin bundle.
I have the relationship with the user (FOSUserBundle) in the PageEntity.
I want to save the current user which create or change a page.
My guess is get the user object in postUpdate and postPersist methods of the admin class and this object transmit in setUser method.
But how to realize this?
On the google's group I saw
public function setSecurityContext($securityContext) {
$this->securityContext = $securityContext;
}
public function getSecurityContext() {
return $this->securityContext;
}
public function prePersist($article) {
$user = $this->getSecurityContext()->getToken()->getUser();
$appunto->setOperatore($user->getUsername());
}
but this doesn't work
In the admin class you can get the current logged in user like this:
$this->getConfigurationPool()->getContainer()->get('security.token_storage')->getToken()->getUser()
EDIT based on feedback
And you are doing it this? Because this should work.
/**
* {#inheritdoc}
*/
public function prePersist($object)
{
$user = $this->getConfigurationPool()->getContainer()->get('security.token_storage')->getToken()->getUser();
$object->setUser($user);
}
/**
* {#inheritdoc}
*/
public function preUpdate($object)
{
$user = $this->getConfigurationPool()->getContainer()->get('security.token_storage')->getToken()->getUser();
$object->setUser($user);
}
Starting with symfony 2.8, you should use security.token_storage instead of security.context to retrieve the user. Use constructor injection to get it in your admin:
public function __construct(
$code,
$class,
$baseControllerName,
TokenStorageInterface $tokenStorage
) {
parent::__construct($code, $class, $baseControllerName);
$this->tokenStorage = $tokenStorage;
}
admin.yml :
arguments:
- ~
- Your\Entity
- ~
- '#security.token_storage'
then use $this->tokenStorage->getToken()->getUser() to get the current user.
I was dealing with this issue on the version 5.3.10 of symfony and 4.2 of sonata. The answer from greg0ire was really helpful, also this info from symfony docs, here is my approach:
In my case I was trying to set a custom query based on a property from User.
// ...
use Symfony\Component\Security\Core\Security;
final class YourClassAdmin extends from AbstractAdmin {
// ...
private $security;
public function __construct($code, $class, $baseControllerName, Security $security)
{
parent::__construct($code, $class, $baseControllerName);
// Avoid calling getUser() in the constructor: auth may not
// be complete yet. Instead, store the entire Security object.
$this->security = $security;
}
// customize the query used to generate the list
protected function configureQuery(ProxyQueryInterface $query): ProxyQueryInterface
{
$query = parent::configureQuery($query);
$rootAlias = current($query->getRootAliases());
// ..
$user = $this->security->getUser();
// ...
return $query;
}
}