Access Symfony session values from external application

岁酱吖の 提交于 2019-12-02 01:40:05

I managed to access security context by doing this:
In reponsivefilemanager/config/config.php add:

require_once '../../vendor/autoload.php';
require_once '../../app/bootstrap.php.cache';
require_once '../../app/AppKernel.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernel;

$kernel = new AppKernel('dev', true);
//$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
$kernel->boot();

$session = new \Symfony\Component\HttpFoundation\Session\Session($kernel->getContainer()->get('session.storage'));
$session->start();
$request = Request::createFromGlobals();
$request->setSession($session);
$event = new GetResponseEvent($kernel->getContainer()->get('http_kernel'),$request, HttpKernel::MASTER_REQUEST);

$firewall = $kernel->getContainer()->get('security.firewall');
$firewall->onKernelRequest($event);
if(!$kernel->getContainer()->get('security.context')->isGranted('ROLE_ADMIN')) die("Access Denied");

Of course you should change autoload.php, bootstrap.php.cache & AppKernel.php paths according to your file structure.
This has two problems:

  • You should use $kernel = new AppKernel('prod', false); when using prod mode (app.php) and $kernel = new AppKernel('dev', true); when using dev mode (app_dev.php)
  • This has a problem when a non-logged in user attempts to access filemanager and gives symfony's Access Denied error ; however, it does the job and prevents non-granted user to use the file manager

I'm working on solving the problems; and I'll post the result here.

Good luck

You can read the symfony session like this :

// start session
session_start();

// check for symfony2 attrs first
if (isset($_SESSION['_sf2_attributes'])) {

    // check for security main information
    if (isset($_SESSION['_sf2_attributes']['_security_main'])) {

        // we are safe to go :)

        // change it , to meet your path
        require_once __DIR__ . '/../../../app/autoload.php';

       /**
        * @var Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken 
       */
        $security = unserialize($_SESSION['_sf2_attributes']['_security_main']);

        $roles = $security->getRoles();
        $user = $security->getUser();

       // do your logic here

     } else {
        die('Access Denied');
     }
  } else {
    die('Access Denied');
  }

in config.php before session_start(); add

require_once __DIR__.'/../../../../../app/bootstrap.php.cache';
require_once __DIR__.'/../../../../../app/AppKernel.php';

use Symfony\Component\HttpFoundation\Request;

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();

$request = Request::createFromGlobals();
$response = $kernel->handle($request);

$isSymfony2Authenticated = $kernel->getContainer()->get('security.context')->getToken() != null && ($kernel->getContainer()->get('security.context')->isGranted('ROLE_ADMIN') || $kernel->getContainer()->get('security.context')->isGranted('ROLE_SUPER_ADMIN'));
if ( ! $isSymfony2Authenticated) {
    die('Access denied!');
}

This will check if user has ROLE_ADMIN or ROLE_SUPER_ADMIN

Symfony Session from externals:

Hello, for access from an external application to symfony session. I hope it good, bye.

app/config/config.yml

framework:
    session:
        handler_id: session.handler.native_file
        save_path: "%kernel.root_dir%/sessions"

PHP Class content:

/**
 * @var array
 */
protected $sesion;

/**
 * Obtiene los datos del usuario logeado en symfony
 *
 * @return string
 */
public function getSesion()
{
    try
    {
        if (!isset($_COOKIE['PHPSESSID'])) {
            throw new \Exception("No se encontro la cookie de sesion.", 1);
        }

        $path = '\\path\\proyect';
        $archivo_sesion = $path[0].'\\app\\sessions\\sess_'.$_COOKIE['PHPSESSID'];

        if (!file_exists($archivo_sesion)) {
            throw new \Exception("No se encontro el archivo de sesion.", 1);                
        }

        $sesion = file_get_contents($archivo_sesion);
        $sesion = str_replace('_sf2_attributes|', '', $sesion);
        $sesion = unserialize($sesion);

        if (!isset($sesion['_security_default'])) {
            throw new \Exception("Usuario no autorizado.", 1);
        }
    } catch (\Exception $e) {
        header('Location: '.$sesion['_security.default.target_path'].'login');
        die();            
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!