加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 17:47:23 所属栏目:PHP教程 来源:网络整理
导读:我目前正在关注 Security Service Provider的Silex教程. 我有登录表单,我的check_path使用以下代码设置为/ login_check: $app-register(new SilexProviderSecurityServiceProvider(),array( 'security.firewalls' = array( 'admin' = array( 'pattern' =
我目前正在关注 Security Service Provider的Silex教程.

我有登录表单,我的check_path使用以下代码设置为/ login_check:

$app->register(new SilexProviderSecurityServiceProvider(),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处获取挂钩,但您可以添加一个处理程序,该处理程序将在成功登录后由Silex调用:

$app['security.authentication.success_handler.admin'] = 
  $app->share(function() use ($app) {
    return new CustomAuthenticationSuccessHandler($app['security.http_utils'],array(),$app);
  });

CustomAuthenticationSuccessHandler扩展了DefaultAuthenticationSuccessHandler(示例):

use SymfonyComponentSecurityHttpAuthenticationDefaultAuthenticationSuccessHandler;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentSecurityHttpHttpUtils;
use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
use SilexApplication;

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()更新用户数据并记录上次登录的日期时间 – 您可以在那里执行任何其他操作.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读