6

我正在使用 Silex,无法在模板中使用 is_granted 函数。我在文档中找不到任何关于为什么这不起作用的信息。有什么提示吗?

$app->register(new Silex\Provider\SecurityServiceProvider());

$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => __DIR__.'/../templates',
    'twig.options' => array('cache' => __DIR__.'/../cache'),
));

$app['debug'] = true;

$app['security.firewalls'] = array(
    'login' => array(
                'pattern' => '^/login$',
        ),
        'secured' => array(
                'pattern' => '^.*$',
                'form' => array('login_path' => '/login', 'check_path' => '/login_check'),
                'users' => array(
                        'admin' => array('ROLE_ADMIN', '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg=='),
                ),
        ),
);

$app->get('/', function() use ($app) {
    return $app['twig']->render('index.html.twig');
});

$app->get('/login', function(Request $request) use ($app) {
    return $app['twig']->render('login.html.twig', array(
            'error'                 => $app['security.last_error']($request),
            //'last_username' => $app['session']->get('_security.last_username'),
    ));
});
4

5 回答 5

11

显然,我还需要添加 symfony/bridge 组件:

将此添加到 composer.json 并更新。

"symfony/twig-bridge": "2.1.*",

嘿......它会像预期的那样工作。

于 2012-10-24T20:27:46.733 回答
4

我不得不使用这个解决方法(还不知道是否有任何缺点)

$function = new Twig_SimpleFunction('is_granted', function($role) use ($app){
    return $app['security']->isGranted($role);
});
$app['twig']->addFunction($function);
于 2013-01-31T21:48:01.820 回答
2

根据Symfony\Component\Security\Core\SecurityContextInterface我们必须提供第二个参数,我们正在尝试评估哪些权利。第二个参数将发送给投票者(例如用户)

$function = new Twig_SimpleFunction('is_granted', function($role, 
$object = null) use ($app){
    return $app['security']->isGranted($role, $object);
});
$app['twig']->addFunction($function);
于 2014-02-18T10:37:49.263 回答
0

问题很可能是由注册课程的顺序引起的。顺序应该是 SecurityServiceProvider 然后启动您的应用程序,然后是 TwigServiceProvider 注册。TwigServiceProvider 检查 $app['security'] 以设置 Twig SecurityExtension。所以顺序很重要

// Security service
$app["security.firewalls"] = array();
$app->register(new Silex\Provider\SecurityServiceProvider());

// Boot your application to call SecurityServiceProvider()->boot()
$app->boot();

// Twig service
$app->register(new Silex\Provider\TwigServiceProvider(), array(
  'twig.path' => sprintf("%s/../views", __DIR__),
));
于 2015-05-22T04:03:09.907 回答
0

如果你使用 Symfony 2.6 组件,它会变成security.authorization_checker而不是security,如下所示:

$function = new Twig_SimpleFunction('is_granted', function($role,$object = null) use ($app){
    return $app['security.authorization_checker']->isGranted($role,$object);
});
$app['twig']->addFunction($function);
于 2017-10-30T20:19:08.200 回答