Silex/Symfony Security Firewall Access user token outside the secured area

让人想犯罪 __ 提交于 2019-12-31 05:48:07

问题


I use Silex and the SecurityProvider, my firewall :

$app->register(new Silex\Provider\SecurityServiceProvider(), array(
  'security.firewalls' => array(
    'user' => array(
      'pattern' => '^/user/',
      'form' => array(
        'login_path' => '/connexion',
        'check_path' => '/user/login_check',
        'default_target_path' => 'homepage_user'
        ),
      'logout' => array('logout_path' => '/user/deconnexion')
      ...
      )
    )
  ));

It works ! But I didn't find any way to access to the user object in the template, the symfony synthax doesn't work :

{{ app.user }}

So I add a new global in Twig like this :

$app['twig'] = $app->share($app->extend('twig', function($twig, $app) {
  $token = $app['security']->getToken();
  $user = ($token === null) ? null : $token->getUser();
  $twig->addGlobal('user', $user);
  return $twig;
}));

It works but not outside the secured area: $token is null

My question is simple : How can I access to the user outside of the secured area ?

Thank you

EDIT: I tried to add a firewall with anonymous = true, like this :

$app->register(new Silex\Provider\SecurityServiceProvider(), array(
  'security.firewalls' => array(
    'user' => array(
      'pattern' => '^/user/',
      'form' => array(
        'login_path' => '/connexion',
        'check_path' => '/user/login_check',
        'default_target_path' => 'homepage_user'
        ),
      'logout' => array('logout_path' => '/user/deconnexion'),
      ...
      ),
    'unsecured' => array(
      'anonymous' => true
      )
    )
  ));

But it doesn't work, outside of the secured area, when the user is logged, the token is "anon."


回答1:


But then what you need to do, is put that page under the firewall too. Change the firewall setting so / is the firewall, and add ACL so anonymous can also enter to /. Then you can have there user data.

Where you load in your header data, you check that the user is authenticated or not, cause this is the main thing, isGranted('IS_AUTHENTICATED_REMEMBERED') and depending on the result, you will include different template file.




回答2:


The user information is only available in secured areas, to get access also outside of these areas you must allow anonymous users as described in the documentation:

$app['security.firewalls'] = array(
'unsecured' => array(
    'anonymous' => true,

    // ...
),


来源:https://stackoverflow.com/questions/20154988/silex-symfony-security-firewall-access-user-token-outside-the-secured-area

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!