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

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']);
    }),
),

);

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

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

这很原始 - 您是否考虑过使用 MVC 框架?会为你节省很多时间。

为什么不创建控制器?

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

您可以通过在防火墙中启用匿名用户和经过身份验证的用户,然后使用访问规则,将对 /accounts 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 doc for more information on authorization. Also if you want to know more about access control without roles check this out