允许用户和匿名者查看网站,但保护部分网站的安全


Allowing users and anonymous to view website, but securing part of it

我遇到了问题:我想允许用户和匿名查看网站,并且只允许用户采取某些操作(我已经讨论过了)。问题是某些路径(/account等)应该只有登录的用户才能访问。我真的很努力地配置我的secure.php,但是,要么匿名者可以访问/account,要么我不能访问除/account/之外的任何地方的登录用户。。。

两者都试过:

$app['security.firewalls'] = array(
'secured' => array(
    'pattern' => '/account',
    'form' => array('login_path' => '/login', 'check_path' => '/account/login_check'),
    'logout' => array('logout_path' => '/account/logout', 'invalidate_session' => true),
    'users' => $app->share(function () use ($app) {
        return new UserProvider($app['db']);
    }),
),
'unsecured' => array(
  'pattern'=> '/',
    'anonymous' => true,
)
);

$app['security.firewalls'] = array(
'secured' => array(
    'pattern' => '/account',
    'anonymous'=> true,
    'form' => array('login_path' => '/login', 'check_path' => '/account/login_check'),
    'logout' => array('logout_path' => '/account/logout', 'invalidate_session' => true),
    'users' => $app->share(function () use ($app) {
        return new UserProvider($app['db']);
    }),
),
);

您需要在授权步骤中执行此操作,因此必须配置security.access_rules密钥。

您可以通过在单个防火墙中启用匿名和经过身份验证的用户来实现这一点,然后使用访问规则,将对/帐户URI的访问限制为只允许经过身份验证用户:

<?php
$app['security.firewalls'] = array(
'secured' => array(
    'pattern' => '^.*$',
    'anonymous' => true,
    'form' => array('login_path' => '/login', 'check_path' => '/account/login_check'),
    'logout' => array('logout_path' => '/account/logout', 'invalidate_session' => true),
    'users' => $app->share(function () use ($app) {
        return new UserProvider($app['db']);
    }),
);
// By using authorization the access to the /account/* is protected to
// users with the ROLE_USER (you can be more creative here if you want)
// and with the second rule the whole site is allowed to non authenticated
// users (remember the /login path must not be protected!)
$app['security.access_rules'] = array(
  // this could be also array('^/account', 'ROLE_USER')
  array('^/account', 'IS_AUTHENTICATED_FULLY'),
  array('^.*$', 'IS_AUTHENTICATED_ANONYMOUSLY')
);

有关授权的更多信息,请参阅Symfony文档。此外,如果您想了解更多关于无角色访问控制的信息,请查看

最简单的方法是在页眉中设置会话。

if(!isset($_SESSION["logged_in"])){
  header("Location: http://www.example.com/");
}

这是相当原始的-你想过使用MVC框架吗?会为你节省很多时间。

为什么不创建控制器?