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


我正在尝试在Symfony 2.1项目中实现安全功能,其中管理员可以使用初始密码创建用户,然后当用户第一次登录时自动触发更改密码处理程序。

我遇到了覆盖FOSUserBundle类的问题,我认为这肯定已经以某种方式构建,至少在某种程度上,尽管我无法在任何地方的文档中看到它。

我想在实体中使用credentials_expired标志。管理员创建用户时,将设置为1.当用户首次登录时,将检查credentials_expired,而不是抛出异常,将触发change-password。我做到了这么远。

然后ChangePasswordController将确保密码实际更改(这似乎不是FOS中的默认行为)并且credentials_expired设置为0.这就是我被困住的地方。有这么多层服务我似乎无法正确定制。


1404
2018-03-06 19:56


起源

你可以再详细一点吗?有很多方法可以解决这个问题。发布您的代码有助于我们确定如何继续。无论如何,使用比标志更可能的角色可能是一个好主意,因为您可以使用symfony防火墙进行管理。因此,具有CREDENTIAL_EXPIRED角色的人无法访问整个网络,并且他们被困在一种迫使他们更改密码的形式中。 - Manu
代码是FOSUserBundle。这个角色是一个好主意,因为它不需要扩展类。我会试一试。谢谢。 - David


答案:


这是详细的答案。感谢Manu的跳板!

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

"friendsofsymfony/user-bundle":"dev-master"

以下内容全部包含在我自己的用户包中,该用户包按照安装文档中的说明扩展了FOSUserBundle。

PortalFlare /包/ UserBundle /资源/配置/的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 /包/ UserBundle /事件监听/ 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 /包/ UserBundle /事件监听/ 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实际上没有确保用户更改密码的问题是另一天的问题。

我希望这可以帮助别人。


12
2018-03-08 00:15





一个好方法可能是开始定义一个ROLE_USER,它将成为可以访问整个应用程序的角色。当用户注册时,会自动为他添加ROLE_CREDENTIAL_EXPIRED或类似内容。运用 JMSSecurityExtraBundle,您可以在控制器中使用注释,确定具有给定角色的用户是否可以访问。还要查看文档如何 Symfony处理HTTP身份验证


4
2018-03-07 15:42



可怜的@Manu值得一个upvote我认为:) - Darragh Enright
谢谢您的好意!谢谢@DarraghEnright :) - Manu