如何使用FOSUserBundle强制用户更改密码?

12
我正试图在Symfony 2.1项目中实现一个安全功能,使管理员可以创建一个带有初始密码的用户,当用户第一次登录时,自动触发更改密码处理程序。
我遇到了重写FOSUserBundle类的问题,我认为这肯定已经内置了某些部分,尽管我在文档中找不到它。
我想在实体中使用credentials_expired标志。当管理员创建用户时,这将被设置为1。当用户第一次登录时,检查credentials_expired,而不是抛出异常,触发更改密码操作。我已经做到了这一点。
然后,ChangePasswordController会确保密码实际上已更改(这似乎不是FOS的默认行为),并将credentials_expired设置为0。这就是我卡住的地方。有太多层服务,我似乎无法正确地定制事物。

你能具体一点吗?有很多方法可以解决这个问题。发布你的代码将帮助我们确定如何继续。无论如何,使用角色而不是标志可能是一个好主意,因为你可以通过Symfony防火墙来管理它。因此,拥有CREDENTIAL_EXPIRED角色的人无法访问整个网站,并被困在一个强制他们更改密码的表单中。 - Manu
代码将是FOSUserBundle。角色是一个很好的想法,因为它不需要扩展类。我会尝试一下。谢谢。 - David
2个回答

15

以下是详细答案。感谢Manu提供的支持!

首先,请确保在composer.json文件中获取正确的FOSUserBundle(使用"dev-master",而不是"*"):

"friendsofsymfony/user-bundle":"dev-master"
以下所有内容都包含在我的用户捆绑包中,该捆绑包按照安装文档的指示扩展了FOSUserBundle。
PortalFlare/Bundle/UserBundle/Resources/config/services.xml:
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services  http://symfony.com/schema/dic/services/services-1.0.xsd">

<parameters>
    <parameter key="portal_flare_user.forcepasswordchange.class">PortalFlare\Bundle\UserBundle\EventListener\ForcePasswordChange</parameter>
    <parameter key="portal_flare_user.passwordchangelistener.class">PortalFlare\Bundle\UserBundle\EventListener\PasswordChangeListener</parameter>
</parameters>

<services>
    <service id="portal_flare_user.forcepasswordchange" class="%portal_flare_user.forcepasswordchange.class%">
        <argument type="service" id="router" />
        <argument type="service" id="security.context" />
        <argument type="service" id="session" />
        <tag name="kernel.event_listener" event="kernel.request" method="onCheckStatus" priority="1" />
    </service>
    <service id="portal_flare_user.passwordchange" class="%portal_flare_user.passwordchangelistener.class%">
        <argument type="service" id="router" />
        <argument type="service" id="security.context" />
        <argument type="service" id="fos_user.user_manager" />
        <tag name="kernel.event_subscriber" />
    </service>
</services>

</container>

PortalFlare/Bundle/UserBundle/EventListener/ForcePasswordChange.php:

    <?php

namespace PortalFlare\Bundle\UserBundle\EventListener;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\HttpFoundation\Session\Session;

/**
 * @Service("request.set_messages_count_listener")
 *
 */
class ForcePasswordChange {

  private $security_context;
  private $router;
  private $session;

  public function __construct(Router $router, SecurityContext $security_context, Session $session) {
    $this->security_context = $security_context;
    $this->router           = $router;
    $this->session          = $session;

  }

  public function onCheckStatus(GetResponseEvent $event) {

    if (($this->security_context->getToken()) && ($this->security_context->isGranted('IS_AUTHENTICATED_FULLY'))) {

      $route_name = $event->getRequest()->get('_route');

      if ($route_name != 'fos_user_change_password') {

        if ($this->security_context->getToken()->getUser()->hasRole('ROLE_FORCEPASSWORDCHANGE')) {

          $response = new RedirectResponse($this->router->generate('fos_user_change_password'));
          $this->session->setFlash('notice', "Your password has expired. Please change it.");
          $event->setResponse($response);

        }

      }

    }

  }

} 

PortalFlare/Bundle/UserBundle/EventListener/PasswordChangeListener.php:

<?php
namespace PortalFlare\Bundle\UserBundle\EventListener;

use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Doctrine\UserManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\SecurityContext;

/**
 * Listener responsible to change the redirection at the end of the password change
 */
class PasswordChangeListener implements EventSubscriberInterface {
  private $security_context;
  private $router;
  private $usermanager;

  public function __construct(UrlGeneratorInterface $router, SecurityContext $security_context, UserManager $usermanager) {
    $this->security_context = $security_context;
    $this->router           = $router;
    $this->usermanager      = $usermanager;
  }

  /**
   * {@inheritDoc}
   */
  public static function getSubscribedEvents() {
    return array(
      FOSUserEvents::CHANGE_PASSWORD_SUCCESS => 'onChangePasswordSuccess',
    );
  }

  public function onChangePasswordSuccess(FormEvent $event) {

    $user = $this->security_context->getToken()->getUser();
    $user->removeRole('ROLE_FORCEPASSWORDCHANGE');
    $this->usermanager->updateUser($user);

    $url = $this->router->generate('_welcome');
    $event->setResponse(new RedirectResponse($url));
  }
}

FOSUserBundle并未确保用户更改密码的问题,暂且不表。

希望这能帮到有需要的人。


5
一个好的方法可能是先定义一个ROLE_USER,这个角色将能够访问整个应用程序。当用户注册时,自动添加ROLE_CREDENTIAL_EXPIRED或类似的角色。使用JMSSecurityExtraBundle,您可以在控制器中使用注释,决定具有特定角色的用户是否可以访问。还要查看Symfony如何处理HTTP身份验证的文档。

非常感谢你!谢谢 @DarraghEnright :) - Manu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接