我目前正在关注Security Service Provider的Silex教程。
我的登录表单正常工作,我的check_path使用以下代码设置为/ login_check:
$app->register(new Silex\Provider\SecurityServiceProvider(), array(
'security.firewalls' => array(
'admin' => array(
'pattern' => '^/contacts/add',
'form' => array('login_path' => '/login', 'check_path' => '/login_check'),
'users' => array(
'admin' => array('ROLE_ADMIN', '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg=='),
),
)
)
));
但是,我不知道如何在silex中验证用户登录,因为没有login_check的示例代码:
$app->post('/login_check', function(Request $request) use ($app) {
// What now??
});
答案 0 :(得分:7)
Silex / Symfony将为您处理身份验证检查,因此您将无法在路由/login_check
处获取挂钩,但您可以添加一个处理程序,该处理程序将在成功登录后由Silex调用:
$app['security.authentication.success_handler.admin'] =
$app->share(function() use ($app) {
return new CustomAuthenticationSuccessHandler($app['security.http_utils'],
array(), $app);
});
CustomAuthenticationSuccessHandler扩展了DefaultAuthenticationSuccessHandler(示例):
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationSuccessHandler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Silex\Application;
class CustomAuthenticationSuccessHandler extends DefaultAuthenticationSuccessHandler
{
protected $app = null;
public function __construct(HttpUtils $httpUtils, array $options, Application $app)
{
parent::__construct($httpUtils, $options);
$this->app = $app;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
$user = $token->getUser();
$data = array(
'last_login' => date('Y-m-d H:i:s')
);
// save the last login of the user
$this->app['account']->updateUserData($user->getUsername(), $data);
return $this->httpUtils->createRedirectResponse($request, $this->determineTargetUrl($request));
}
}
在此示例中onAuthenticationSuccess()
更新用户数据并记录上次登录的日期时间 - 您可以在那里执行任何其他操作。
还存在身份验证失败和注销的处理程序。