在我的应用程序中,我在 routes.php 文件中定义了一个 before()
Hook :
$app->before(function(Request $request) use($app) {
$authAnon = $app['security']->isGranted('IS_AUTHENTICATED_ANONYMOUSLY');
if(!$request->getSession()->get('username') && $authAnon) {
if($request->isXmlHttpRequest()) {
// return 401/HTTP_UNAUTHORIZED response
$response = new Response();
$response->setStatusCode(Response::HTTP_UNAUTHORIZED);
$response->headers->set('Reason', 'SESSION_EXPIRED');
$response->headers->set('WWW-Authenticate', 'MyAuthScheme realm="app:login"');
return $response;
}
return new RedirectResponse('login', 301);
}
}
但这会导致 $app['security']
未被找到/定义:
InvalidArgumentException in Container.php line 96: Identifier "security" is not defined.
我的安全设置如下所示:
$app->register(new Silex\Provider\SecurityServiceProvider(), array(
'security.firewalls' => array(
'login' => array(
'pattern' => '^/login$',
),
'secured' => array(
'pattern' => '^.*$',
'form' => array('login_path' => '/login', 'check_path' => '/login_check'),
'logout' => array('logout_path' => '/logout', 'invalidate_session' => true),
'users' => array(
'admin' => array('ROLE_ADMIN', 'hashed_pwd'),
'user' => array('ROLE_USER', 'hashed_pwd'),
),
),
)
));
$app['security.role_hierarchy'] = array(
'ROLE_ADMIN' => array('ROLE_USER'),
);
$app['security.access_rules'] = array(
array('^/admin', 'ROLE_ADMIN'),
array('^.*$', ['ROLE_USER']),
);
session 和安全提供程序的注册顺序如下所示:
$config_path = __DIR__.'/../app/config/';
require_once $config_path.'session.php';
require_once $config_path.'security.php';
require_once $config_path.'routes/routes.php';
$app->run();
我做错了什么?
编辑
请看一下我下面的答案,看看我最终得到了什么。
最佳答案
我的猜测是,您现在使用的 Symfony 安全组件版本 >= 2.6+,因此根据 Silex docs您不能直接使用服务安全性(如$app['security']
),并且必须使用授权检查器服务($app[' security.authorization_checker']
):
<?php
$app->before(function(Request $request) use($app) {
// This won't work with Symfony Security Component < 2.6
// $authAnon = $app['security']->isGranted('IS_AUTHENTICATED_ANONYMOUSLY');
// Under Symfony 2.6+
$authAnon = $app['security.authorization_checker']->isGranted('IS_AUTHENTICATED_ANONYMOUSLY');
// ...
}
关于php - session 过期时响应 HTTP_UNAUTHORIZED/Redirect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41163697/