php - session 过期时响应 HTTP_UNAUTHORIZED/Redirect

标签 php symfony security session silex

在我的应用程序中,我在 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/

相关文章:

php - PHP和MySql上传大小问题

php - MySQL 慢检查大表中是否存在行

php - 仅显示带有SimpleXMLElement的第一个对象

ios - 如何让 iOS Safari 为基本认证网站保存密码?

php - Laravel 5.5 查询生成器其中Raw不返回结果,但原始SQL返回结果

forms - 如何选择 'choices' findall后表单的显示字段?

php - 当点击网站上的链接时,如何写入 Symfony2 中的数据库?

email - 如何在 FOSUserBundle 中为 Controller 重置设置 sender_name?

javascript - Node.JS,我的密码在 RAM 中安全吗?

ASP.NET SSL 身份验证票证安全吗?