我正在使用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'),
));
});
答案 0 :(得分:9)
显然,我还需要添加symfony / bridge组件:
将此添加到composer.json并更新。
"symfony/twig-bridge": "2.1.*",
嘿......它会像预期的那样奏效。
答案 1 :(得分:4)
我不得不使用这种解决方法(不知道是否有任何缺点)
$function = new Twig_SimpleFunction('is_granted', function($role) use ($app){
return $app['security']->isGranted($role);
});
$app['twig']->addFunction($function);
答案 2 :(得分: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);
答案 3 :(得分: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__),
));
答案 4 :(得分:0)
如果您使用Symfony 2.6组件,它将变为 security.authorization_checker ,而不是安全,如:
$function = new Twig_SimpleFunction('is_granted', function($role,$object = null) use ($app){
return $app['security.authorization_checker']->isGranted($role,$object);
});
$app['twig']->addFunction($function);