2

I have a third party application (responsivefilemanager plugin for TinyMCE) that I can't re-write it using Symfony2.
I need to protect it against unauthorized users.
Is it possible to access Symfony2's session variables (user, roles , etc) from external application? How?
I tried to do session_start() and read $_SESSION variable, but it is empty!
My config.yml is:

imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: @ar1y4nArticleBundle/Resources/config/admin.yml }

framework:
    #esi:             ~
    translator:      { fallback: %locale% }
    secret:          %secret%
    router:
        resource: "%kernel.root_dir%/config/routing.yml"
        strict_requirements: ~
    form:            ~
    csrf_protection: ~
    validation:      { enable_annotations: true }
    templating:
        engines: ['twig']
        #assets_version: SomeVersionScheme
    default_locale:  "%locale%"
    trusted_proxies: ~
    session:         ~
    fragments:       ~

# Twig Configuration
twig:
    debug:            %kernel.debug%
    strict_variables: %kernel.debug%

# Assetic Configuration
assetic:
    debug:          %kernel.debug%
    use_controller: false
    bundles:        [ ]
    #java: /usr/bin/java
    filters:
        cssrewrite: ~
        #closure:
        #    jar: %kernel.root_dir%/Resources/java/compiler.jar
        #yui_css:
        #    jar: %kernel.root_dir%/Resources/java/yuicompressor-2.4.7.jar

# Doctrine Configuration
doctrine:
    dbal:
        driver:   %database_driver%
        host:     %database_host%
        port:     %database_port%
        dbname:   %database_name%
        user:     %database_user%
        password: %database_password%
        charset:  UTF8
        types: #this is about this line and line below
            json:     Sonata\Doctrine\Types\JsonType
        # if using pdo_sqlite as your database driver, add the path in parameters.yml
        # e.g. database_path: %kernel.root_dir%/data/data.db3
        # path:     %database_path%

    orm:
        auto_generate_proxy_classes: %kernel.debug%
        auto_mapping: true

# Swiftmailer Configuration
swiftmailer:
    transport: %mailer_transport%
    host:      %mailer_host%
    username:  %mailer_user%
    password:  %mailer_password%
    spool:     { type: memory }

fos_user:
    db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
    firewall_name: main
    user_class:     ar1y4n\UserBundle\Entity\User

    group:
        group_class: ar1y4n\UserBundle\Entity\Group  

sonata_block:
    default_contexts: [cms]
    blocks:
        sonata.admin.block.admin_list:
            contexts:   [admin]

        #sonata.admin_doctrine_orm.block.audit:
        #    contexts:   [admin]

        sonata.block.service.text:
        sonata.block.service.rss:

        sonata.user.block.menu:    # used to display the menu in profile pages
        sonata.user.block.account: # used to display menu option (login option)

        # Some specific block from the SonataMediaBundle
        #sonata.media.block.media:
        #sonata.media.block.gallery:
        #sonata.media.block.feature_media:

knp_menu:
    twig:  # use "twig: false" to disable the Twig extension and the TwigRenderer
        template: knp_menu.html.twig
    templating: false # if true, enables the helper for PHP templates
    default_renderer: twig # The renderer to use, list is also available by default

sonata_user:
    security_acl: true
    class:                  # Entity Classes
        user:               ar1y4n\UserBundle\Entity\User
        group:              ar1y4n\UserBundle\Entity\Group  

sonata_admin:
    title:      My title
    title_logo: bundles/ar1y4narticle/images/logo-big.png

genemu_form:
    tinymce:
        enabled: true
        theme:   modern
        configs: {plugins: ["responsivefilemanager advlist autolink lists link image charmap print preview hr anchor pagebreak","searchreplace wordcount visualblocks visualchars code fullscreen","insertdatetime media nonbreaking save table contextmenu directionality", "emoticons template paste textcolor"],toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",toolbar2: "print preview media | forecolor backcolor emoticons | responsivefilemanager",image_advtab: true, external_filemanager_path:"/filemanager/",filemanager_title:"Responsive Filemanager" ,external_plugins: { "filemanager" : "/filemanager/plugin.min.js"}}                 
2
  • Are your sessions in memory or a data store? Commented Dec 31, 2013 at 15:04
  • @Seth: I'm using default config (~) for session in framework section of config.yml that should be memory I think. please check my edit on question. Commented Dec 31, 2013 at 16:37

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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');
  }

Comments

1

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

For Symfony 4.4

require dirname(__DIR__).'/../../../vendor/autoload.php';// relative path from your app
require dirname(__DIR__).'/../../../config/bootstrap.php';// relative path from your app

use App\Kernel;
use Symfony\Component\HttpFoundation\Request;

/*if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? $_ENV['TRUSTED_PROXIES'] ?? false) {
    Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST);
}

if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? $_ENV['TRUSTED_HOSTS'] ?? false) {
    Request::setTrustedHosts([$trustedHosts]);
}*/

$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$request = Request::createFromGlobals();
$kernel->handle($request);
if(!$kernel->getContainer()->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) die("Access Denied");

Comments

0

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();            
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.