symfony2 logout - php

My problem is capture user logout. the code what i have is:
public function onAuthenticationFailure(Request $request, AuthenticationException $exception){
return new Response($this->translator->trans($exception->getMessage()));
}
public function logout(Request $request, Response $response, TokenInterface $token)
{
$empleado = $token->getUser();
$log = new Log();
$log->setFechalog(new \DateTime('now'));
$log->setTipo("Out");
$log->setEntidad("");
$log->setEmpleado($empleado);
$this->em->persist($log);
$this->em->flush();
}
public function onLogoutSuccess(Request $request) {
return new RedirectResponse($this->router->generate('login'));
}
The problem is I can not access the user token TokenInterface when you are running the logout function?

To get token, you must inject with security context.
1. Create class Logout listener, something like this:
namespace Yourproject\Yourbundle\Services;
...
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
use Symfony\Component\Security\Core\SecurityContext;
class LogoutListener implements LogoutSuccessHandlerInterface {
private $security;
public function __construct(SecurityContext $security) {
$this->security = $security;
}
public function onLogoutSuccess(Request $request) {
$user = $this->security->getToken()->getUser();
//add code to handle $user here
//...
$response = RedirectResponse($this->router->generate('login'));
return $response;
}
}
2. And then in service.yml, add this line:
....
logout_listener:
class: Yourproject\Yourbundle\Services\LogoutListener
arguments: [#security.context]
That's it, may it helps.

See http://symfony.com/doc/current/reference/configuration/security.html
security.yml
secured_area:
logout:
path: /logout
**success_handler: logout_listener**

Take a look here were you can overwrite any controller of the bundle:
http://symfony.com/doc/current/cookbook/bundles/inheritance.html

Related

Symfony 4.4: How to create Keycloak authentication in functionnal tests?

I'm trying to upgrade a Symfony 4.3.6 application to v4.4.
The app uses oauth2-client-bundle to authenticate users with Keycloak. Consequently, users are never persisted in database.
Here is the security config:
security:
providers:
oauth:
id: knpu.oauth2.user_provider
firewalls:
main:
logout:
path: app.logout
anonymous: true
guard:
authenticators:
- App\Security\KeycloakAuthenticator
access_control:
- { path: ^/connect, roles: IS_AUTHENTICATED_ANONYMOUSLY }
-
path: ^/
allow_if: "'127.0.0.1' == request.getClientIp() or is_granted('IS_AUTHENTICATED_FULLY')"
And here is the KeycloakAuthenticator service:
<?php
namespace App\Security;
use App\Entity\User; // extends KnpU\OAuth2ClientBundle\Security\User\OAuthUser
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use KnpU\OAuth2ClientBundle\Client\Provider\KeycloakClient;
use KnpU\OAuth2ClientBundle\Security\Authenticator\SocialAuthenticator;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
class KeycloakAuthenticator extends SocialAuthenticator
{
private $clientRegistry;
private $router;
public function __construct(ClientRegistry $clientRegistry, RouterInterface $router)
{
$this->clientRegistry = $clientRegistry;
$this->router = $router;
}
public function supports(Request $request)
{
return 'connect_keycloak_check' === $request->attributes->get('_route');
}
public function getCredentials(Request $request)
{
return $this->fetchAccessToken($this->getKeycloakClient());
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$keycloakUser = $this->getKeycloakClient()->fetchUserFromToken($credentials);
$user = new User($keycloakUser->getName(), ['IS_AUTHENTICATED_FULLY', 'ROLE_USER']);
$user->setEmail($keycloakUser->getEmail())
->setName($keycloakUser->getName())
->setLocale($keycloakUser->toArray()['locale'] ?? 'fr')
;
return $user;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
// On success, let the request continue
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$message = strtr($exception->getMessageKey(), $exception->getMessageData());
return new Response($message, Response::HTTP_FORBIDDEN);
}
public function start(Request $request, AuthenticationException $authException = null)
{
return new RedirectResponse($this->router->generate('app.keycloak_start'), Response::HTTP_TEMPORARY_REDIRECT);
}
private function getKeycloakClient(): KeycloakClient
{
return $this->clientRegistry->getClient('keycloak');
}
}
Functional tests are developped according to the official documentation:
public function testHomePage()
{
$client = static::createClient();
$session = $client->getContainer()->get('session');
$firewallName = 'main';
$token = new PostAuthenticationGuardToken(new User('foo', ['ROLE_USER']), $firewallName, $roles);
$session->set('_security_'.$firewallName, serialize($token));
$session->save();
$cookie = new Cookie($session->getName(), $session->getId());
$client->getCookieJar()->set($cookie);
$client->request('GET', '/');
$this->assertTrue($client->getResponse()->isSuccessful());
}
Until now, tests pass, everything is fine.
But since I upgraded Symfony to 4.4, the method ControllerTrait::getUser() returns null and I'm facing the following error when running functional tests:
Error : Call to a member function getUsername() on null
I except to get the current user as usual when calling $this->getUser().
I tried to manually set the token in the security.token_storage but the error still persists.
I also tried to force authentication by removing the part "'127.0.0.1' == request.getClientIp() in the allow_if section of "security.yaml", and the response is now a 307 Temporary Redirect to the Keycloak service.
Did the behavior of $this->getUser() change between this 2 versions ?
Thank you for your help

How to make some security checks before the user will be granted to log-in (pre-login)?

According to this "Old" article Is there any sort of "pre login" event or similar? I can extend UsernamePasswordFormAuthenticationListener to add some code pre-login.
In symfony3 seems that there's no security.authentication.listener.form.class parameter, so how can I reach the same result without changing symfony security_listener.xml config file?
To perform some pre/post-login checks (that means before/after the user authentication) one of the most simple and flexible solutions, offered by the Symfony framework, is to learn How to Create and Enable Custom User Checkers.
If you need more control and flexibility the best option is to learn How to Create a Custom Authentication System with Guard.
Take a look at the simple implementation example below:
security.yml
firewall_name:
guard:
authenticators:
- service_name_for_guard_authenticator
entry_point: service_name_for_guard_authenticator <-- important to add a default one (as described in the docs) if you have many custom authenticators (facebook...)
service.xml
<service id="service_name_for_guard_authenticator"
class="AppBundle\ExampleFolderName\YourGuardAuthClassName">
<argument type="service" id="router"/>
<argument type="service" id="security.password_encoder"/>
</service>
YourGuardAuthClassName.php
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoder;
class YourGuardAuthClassName extends AbstractGuardAuthenticator
{
private $router;
private $passwordEncoder;
public function __construct(
Router $router,
UserPasswordEncoder $passwordEncoder)
{
$this->router = $router;
$this->passwordEncoder = $passwordEncoder;
}
public function start(Request $request, AuthenticationException $authException = null)
{
$response = new RedirectResponse($this->router->generate('your_user_login_route_name'));
return $response;
}
public function getCredentials(Request $request)
{
# CHECK IF IT'S THE CHECK LOGIN ROUTE
if ($request->attributes->get('_route') !== 'your_user_login_route_name'
|| !$request->isMethod('POST')) {
return null;
}
# GRAB ALL REQUEST PARAMETERS
$params = $request->request->all();
# SET LOGIN CREDENTIALS
return array(
'email' => $params['email'],
'password' => $params['password'],
);
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$email = $credentials['email'];
$user = $userProvider->loadUserByUsername($email);
if (! $user){
throw new UsernameNotFoundException();
}
return $user;
}
public function checkCredentials($credentials, UserInterface $user)
{
# YOU CAN ADD YOUR CHECKS HERE!
if (! $this->passwordEncoder->isPasswordValid($user, $credentials['password'])) {
throw new BadCredentialsException();
}
return true;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
# OYU CAN ALSO USE THE EXCEPTIONS TO ADD A FLASH MESSAGE (YOU HAVE TO INJECT YOUR OWN FLASH MESSAGE SERVICE!)
if ($exception instanceof UsernameNotFoundException){
$this->flashMessage->error('user.login.exception.credentials_invalid');
}
if ($exception instanceof BadCredentialsException){
$this->flashMessage->error('user.login.exception.credentials_invalid');
}
return new RedirectResponse($this->router->generate('your_user_login_route_name'));
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
return new RedirectResponse($this->router->generate('your_success_login_route_name'));
}
public function supportsRememberMe()
{
return false;
}
}

Anonymous user object in symfony

I'm using the basic user login/logout system provided with Symfony and it works fine as long as people log in. In that case the $user object is always provided as needed.
The problem is then when logged out (or not lgged in yet) there is no user object. Is there a possibility to have (in that case) a default user object provided with my own default values?
Thanks for your suggestions
Because the solution mention above by #Chopchop (thanks anyway for your effort) didn't work here I wrote a little workaround.
I created a new class called myController which extends Controller. The only function i override is the getUser() function. There I implement it like this:
public function getUser()
{
$user = Controller::getUser();
if ( !is_object($user) )
{
$user = new \ACME\myBundle\Entity\User();
$user->setUserLASTNAME ('RaRa');
$user->setID (0);
// etc...
}
return $user;
}
This works fine for me now. The only problem is that you really have to be careful NOT to forget to replace Controller by myController in all your *Controller.php files. So, better suggestions still welcome.
Works in Symfony 3.3
Using the suggestion of #Sfblaauw, I came up with a solution that uses a CompilerPass.
AppBundle/AppBundle.php
class AppBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new OverrideAnonymousUserCompilerPass());
}
}
OverrideAnonymousUserCompilerPass.php
class OverrideAnonymousCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$definition = $container->getDefinition('security.authentication.listener.anonymous');
$definition->setClass(AnonymousAuthenticationListener::class);
}
}
AnonymousAuthenticationListener.php
class AnonymousAuthenticationListener implements ListenerInterface
{
private $tokenStorage;
private $secret;
private $authenticationManager;
private $logger;
public function __construct(TokenStorageInterface $tokenStorage, $secret, LoggerInterface $logger = null, AuthenticationManagerInterface $authenticationManager = null)
{
$this->tokenStorage = $tokenStorage;
$this->secret = $secret;
$this->authenticationManager = $authenticationManager;
$this->logger = $logger;
}
public function handle(GetResponseEvent $event)
{
if (null !== $this->tokenStorage->getToken()) {
return;
}
try {
// This is the important line:
$token = new AnonymousToken($this->secret, new AnonymousUser(), array());
if (null !== $this->authenticationManager) {
$token = $this->authenticationManager->authenticate($token);
}
$this->tokenStorage->setToken($token);
if (null !== $this->logger) {
$this->logger->info('Populated the TokenStorage with an anonymous Token.');
}
} catch (AuthenticationException $failed) {
if (null !== $this->logger) {
$this->logger->info('Anonymous authentication failed.', array('exception' => $failed));
}
}
}
}
This file is a copy of the AnonymousAuthenticationListener that comes with Symfony, but with the AnonymousToken constructor changed to pass in an AnonymousUser class instead of a string. In my case, AnonymousUser is a class that extends my User object, but you can implement it however you like.
These changes mean that {{ app.user }} in Twig and UserInterface injections in PHP will always return a User: you can use isinstance to tell if it's an AnonymousUser, or add a method isLoggedIn to your User class which returns true in User but false in AnonymousUser.
you can redirect the user not authenticated and force a fake login (to create a user ANONYMOUS)
and set it as well on logout
public function logoutAction(){
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('VendorBundle:User')->findByUserName('annonymous');
$session = $this->getRequest()->getSession();
$session->set('user', $user);
}
and if user is not set
public function checkLoginAction(){
if(!$session->get('user')){
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('VendorBundle:User')->findByUserName('annonymous');
$session = $this->getRequest()->getSession();
$session->set('user', $user);
}
//this->redirect('/');
}
in you security.yml
security:
firewalls:
main:
access_denied_url: /check_login/
access_control:
- { path: ^/$, role: ROLE_USER }
This is only an example i haven't tested (and will probably don't, since i don't get the purpose of doing this:) )
Using Symfony 2.6
Like Gordon says use the authentication listener to override the default anonymous user.
Now you can add the properties that you need to the anonymous user, in my case the language and the currency.
security.yml
parameters:
security.authentication.listener.anonymous.class: AppBundle\Security\Http\Firewall\AnonymousAuthenticationListener
AnonymousAuthenticationListener.php
namespace AppBundle\Security\Http\Firewall;
...
use AppBundle\Security\User\AnonymousUser;
class AnonymousAuthenticationListener implements ListenerInterface
{
...
public function handle(GetResponseEvent $event)
{
...
try {
$token = new AnonymousToken($this->key, new AnonymousUser(), array());
...
}
}
}
AnonymousUser.php
class AnonymousUser implements UserInterface
{
public function getUsername() { return 'anon.'; }
}

In FOSUserBundle, How to initially set user role on REGISTRATION_COMPLETED event?

I'm trying to give each successfully registered user a ROLE_USER role. I'm new to FOSUserBundle, So from what I've read in the documentation, It's done by hocking logic into the controllers.
Here's my NewUserGroupSet Event listener:
<?php
namespace Tsk\TstBundle\EventListener;
use Doctrine\ODM\MongoDB\DocumentManager;
use FOS\UserBundle\Doctrine\UserManager;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class NewUserGroupSet implements EventSubscriberInterface
{
protected $um;
protected $dm;
public function __construct(UserManager $um, DocumentManager $dm)
{
$this->um = $um;
$this->dm = $dm;
}
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_COMPLETED => "onRegistrationSuccess",
);
}
public function onRegistrationSuccess(FilterUserResponseEvent $event)
{
$user = $event->getUser();
$user->setRoles(array('ROLE_USER'));
$this->um->updateUser($user);
$this->dm->flush();
}
}
?>
And is registered as a service as follows:
parameters:
tsk_user.group_set.class: Tsk\TstBundle\EventListener\NewUserGroupSet
services:
tsk_user.group_set:
class: %tsk_user.group_set.class%
arguments: [#fos_user.user_manager, #doctrine.odm.mongodb.document_manager]
tags:
- { name: kernel.event_subscriber }
But when I register a new user, Nothing happens. No roles is being set whatsoever.
Any help would be appreciated.
Have you tried calling addRole() FOSUser entity function,if you notice the setRole function in entity it is looping through the array to roles and passing it to addRole
public function setRoles(array $roles)
{
$this->roles = array();
foreach ($roles as $role) {
$this->addRole($role);
}
return $this;
}
Try with addRole() for single role
public function onRegistrationSuccess(FilterUserResponseEvent $event)
{
$user = $event->getUser();
$user->addRole('ROLE_USER');
$this->um->updateUser($user);
$this->dm->flush();
}

Symfony 2 - Authentication Token Lost After Redirection

I have problem with symfony2 (I have tried the same with Symfony 2.0 & Symfony 2.3 just to see if its a Symfony bug), I am loosing the security token in the next page load / redirect after authentication.
I have created custom authenticator for Symfony 2.3 to authenticate with a 3rd party service as specified here: http://symfony.com/doc/current/cookbook/security/custom_authentication_provider.html
The application authenticates with an external service and sets the token in the callback URL '/success' and i can see from the debug bar that user is authenticated but when i go to '/' (which is under the same firewall) i am getting "A Token was not found in the SecurityContext." Error and user is no longer authenticated.
Here are the files:
security.yml
security:
encoders:
Symfony\Component\Security\Core\User\User: plaintext
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
providers:
users:
entity: { class: AcmeStoreBundle:User, property: email }
firewalls:
login:
pattern: ^/login$
security: false
noa:
pattern: ^/
provider: users
noa: true
logout:
path: /logout
target: /login
access_control:
- { path: ^/success, roles: IS_AUTHENTICATED_ANONYMOUSLY }
NoaUserToken.php
<?php
namespace Acme\StoreBundle\Security\Authentication\Token;
use Symfony\Component\Security\Core\Authentication\Token\AbstractToken;
class NoaUserToken extends AbstractToken
{
public $expires;
public $mobile;
public $email;
public function __construct(array $roles = array())
{
parent::__construct($roles);
parent::setAuthenticated(true);
}
public function getCredentials()
{
return '';
}
}
NoaProvider.php
<?php
namespace Acme\StoreBundle\Security\Authentication\Provider;
use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\NonceExpiredException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Acme\StoreBundle\Security\Authentication\Token\NoaUserToken;
class NoaProvider implements AuthenticationProviderInterface
{
private $userProvider;
private $cacheDir;
public function __construct(UserProviderInterface $userProvider, $cacheDir)
{
$this->userProvider = $userProvider;
$this->cacheDir = $cacheDir;
}
public function authenticate(TokenInterface $token)
{
$userEmail = $token->getUser();
$user = $this->userProvider->loadUserByUsername($userEmail);
if ($user && $this->validateToken($token->expires) && !$user->getHidden()) {
$authenticatedToken = new NoaUserToken($user->getRoles());
$authenticatedToken->expires = $token->expires;
$authenticatedToken->mobile = $token->mobile;
$authenticatedToken->email = $token->email;
$authenticatedToken->setUser($user);
$authenticatedToken->setAuthenticated(true);
return $authenticatedToken;
}
throw new AuthenticationException('The NOA authentication failed.');
}
protected function validateToken($expires)
{
// Check if the token has expired.
if (strtotime($expires) <= time()) {
return false;
}
}
public function supports(TokenInterface $token)
{
return $token instanceof NoaUserToken;
}
}
NoaListener.php
<?php
namespace Acme\StoreBundle\Security\Firewall;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Http\Firewall\ListenerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Acme\StoreBundle\Security\Authentication\Token\NoaUserToken;
class NoaListener implements ListenerInterface
{
protected $securityContext;
protected $authenticationManager;
public function __construct(SecurityContextInterface $securityContext, AuthenticationManagerInterface $authenticationManager)
{
$this->securityContext = $securityContext;
$this->authenticationManager = $authenticationManager;
}
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if (! preg_match('/^\/app_dev.php\/success/', $request->getRequestUri())) {
return;
}
if( $this->securityContext->getToken() ){
return;
}
try {
\NOA_Sso_Web::getInstance()->createSession();
}
catch (Exception $e) {
// Handle error situation here
}
if (isset($_SESSION['userInfo'])) {
$token = new NoaUserToken();
$token->setUser($_SESSION['userInfo']['email']);
$token->mobile = $_SESSION['userInfo']['mobileVerified'] ? $_SESSION['userInfo']['mobile'] : null;
$token->email = $_SESSION['userInfo']['emailVerified'] ? $_SESSION['userInfo']['email'] : null;
$token->expires = $_SESSION['tokenInfo']['expires'];
try {
$authToken = $this->authenticationManager->authenticate($token);
$this->securityContext->setToken($authToken);
return;
} catch (AuthenticationException $failed) {
// Do nothing and go for the default 403
}
}
$this->securityContext->setToken(null);
// Deny authentication with a '403 Forbidden' HTTP response
$response = new Response();
$response->setStatusCode(403);
$event->setResponse($response);
}
}
NoaFactory.php
<?php
namespace Acme\StoreBundle\DependencyInjection\Security\Factory;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface;
class NoaFactory implements SecurityFactoryInterface
{
public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint)
{
$providerId = 'security.authentication.provider.noa.'.$id;
$container
->setDefinition($providerId, new DefinitionDecorator('noa.security.authentication.provider'))
->replaceArgument(0, new Reference($userProvider))
;
$listenerId = 'security.authentication.listener.noa.'.$id;
$listener = $container->setDefinition($listenerId, new DefinitionDecorator('noa.security.authentication.listener'));
return array($providerId, $listenerId, $defaultEntryPoint);
}
public function getPosition()
{
return 'pre_auth';
}
public function getKey()
{
return 'noa';
}
public function addConfiguration(NodeDefinition $node)
{
}
}
DefaultController.php
<?php
namespace Acme\StoreBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Component\HttpFoundation\Response;
class DefaultController extends Controller
{
public function indexAction()
{
$token = $this->container->get('security.context')->getToken();
// Not reached
print '<pre>';
print_r($token->getUser());
print '</pre>';
return $this->render('AcmeStoreBundle:Default:index.html.twig', array('name' => $token->getUser()->gerUsername()));
}
public function loginAction()
{
return $this->render('AcmeStoreBundle:Default:login.html.twig', array());
}
public function successAction()
{
$token = $this->container->get('security.context')->getToken();
$this->container->get('event_dispatcher')->dispatch(
SecurityEvents::INTERACTIVE_LOGIN,
new InteractiveLoginEvent($this->container->get('request'), $token)
);
// This prints the user object
print '<pre>';
print_r($token->getUser());
print '</pre>';
return new Response('<script>//window.top.refreshPage();</script>');
}
}
I have checked all similar questions in stackoverflow and spent around a week to solve this issue, any help is greatly appreciated.
Rather than using $_SESSION in NoaListener, you ought to be using the session interface on the request object. Symfony does its own session management and may ignore or overwrite your session (e.g. it's common to migrate sessions upon successful login to prevent session fixation attacks).
Use $request = $event->getRequest() as you already have, then $request->getSesssion()->get('userInfo'), etc.

Categories