我正在尝试实现一种方法,强制用户在首次登录我的 Symfony 应用程序时更改默认密码。
目前,我已经设置了一个事件监听器来监听 InteractiveLogin
事件。
namespace App\EventListener;
use App\Entity\User;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
class LoginListener
{
private $urlGenerator;
public function __construct(UrlGeneratorInterface $urlGenerator)
{
$this->urlGenerator = $urlGenerator;
}
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
// Get the User entity.
$user = $event->getAuthenticationToken()->getUser();
if ($user->getForcepasswordchange()) {
return new RedirectResponse($this->urlGenerator->generate('force_password_change'));
}
}
}
它主要检查用户实体中是否有一个 bool 标志,该标志对于新用户设置为 true。它会获取用户并且该方法到达 RedirectResponse
行,但最终只是转到主页(默认登录行为)。
我不知道如何强制它不继续登录过程并重定向到我的密码更改页面。
最佳答案
您无法通过监听 InteractiveLoginEvent
来执行此操作。
这个event不包括对响应对象的访问,并且从监听器返回一个响应对象不会让您一无所获,因为没有人会等待监听器返回任何内容。
但是您可以在 RequestEvent
监听器/订阅者上执行此操作:
class PasswordChangeSubscriber implements EventSubscriberInterface
{
private Security $security;
private UrlGeneratorInterface $urlGenerator;
public function __construct(Security $security, UrlGeneratorInterface $urlGenerator)
{
$this->security = $security;
$this->urlGenerator = $urlGenerator;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [['forcePasswordChange', 0]],
];
}
public function forcePasswordChange(RequestEvent $event): void
{
// only deal with the main request, disregard subrequests
if (!$event->isMasterRequest()) {
return;
}
// if we are visiting the password change route, no need to redirect
// otherwise we'd create an infinite redirection loop
if ($event->getRequest()->get('_route') === 'force_password_change') {
return;
}
$user = $this->security->getUser();
// if you do not have a valid user, it means it's not an authenticated request, so it's not our concern
if (!$user instanceof YourUserClass) {
return;
}
// if it's not their first login, and they do not need to change their password, move on
if (!$user->isPasswordChangeRequired()) {
return;
}
// if we get here, it means we need to redirect them to the password change view.
$event->setResponse(new RedirectResponse($this->urlGenerator->generate('force_password_change')));
}
}
关于php - 在 symfony 应用程序中首次登录时强制更改密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60403907/