gpt4 book ai didi

php - Silex check_path 验证用户登录的代码

转载 作者:可可西里 更新时间:2023-10-31 22:11:28 25 4
gpt4 key购买 nike

我目前正在关注 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??
});

最佳答案

Silex/Symfony 将为您处理身份验证检查,因此您不会在路由 /login_check 上 Hook ,但您可以添加一个处理程序,它将在成功登录后由 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() 更新用户数据并记录上次登录的日期时间 - 您可以在那里执行任何其他操作。

还存在身份验证失败和注销的处理程序。

关于php - Silex check_path 验证用户登录的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24317933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com