5. Forgot, reset and change password
You will build the three password pages, reusing the password rules from registration, and handle a link that carries a secret.
Try it: Mezzio · laminas-mvc
Assumes you have done chapter 0, chapter 2 and chapter 3.
| Page | Address | Who uses it |
|---|---|---|
| Forgot password | /forgot-password |
Someone who cannot sign in |
| Reset password | /reset-password?token=… |
The same person, following the emailed link |
| Change password | /change-password |
Someone who is signed in |
<?php
declare(strict_types=1);
namespace App\Forms\Password;
use App\Forms\Csrf\AbstractCsrfProtectedForm;
use Laminas\Filter\StringTrim;
use Laminas\Form\Element\Email;
use Laminas\Form\Element\Submit;
use Laminas\InputFilter\InputFilterProviderInterface;
use Override;
/**
* Asks where to send a password reset link
*
* It checks only the format of the address, so the answer cannot reveal who has an account.
*
* @api
*
* @extends AbstractCsrfProtectedForm<array<string, mixed>>
*/
final class ForgotPasswordForm extends AbstractCsrfProtectedForm implements InputFilterProviderInterface
{
#[Override]
public function getInputFilterSpecification(): array
{
return [
'email' => [
'required' => true,
'filters' => [['name' => StringTrim::class]],
'error_message' => 'Enter an email address in the format name@example.com',
],
];
}
#[Override]
public function init(): void
{
parent::init();
$this->add([
'name' => 'email',
'type' => Email::class,
'options' => ['label' => 'Email address'],
'attributes' => [
'id' => 'email',
'required' => true,
'autocomplete' => 'username',
'autocapitalize' => 'none',
'spellcheck' => 'false',
],
]);
$this->add([
'name' => 'send',
'type' => Submit::class,
'attributes' => ['value' => 'Send reset link'],
]);
}
}
<?php
declare(strict_types=1);
namespace App\Forms\Password;
use Laminas\Form\Element\Submit;
use Override;
/**
* Sets a new password for someone who followed a reset link
*
* The link's token is not a field: check it before showing or processing the form.
*
* @api
*
* @extends AbstractNewPasswordForm<array<string, mixed>>
*/
final class ResetPasswordForm extends AbstractNewPasswordForm
{
#[Override]
public function init(): void
{
parent::init();
$this->addNewPasswordFields('New password', 'Type your new password again');
$this->add([
'name' => 'save',
'type' => Submit::class,
'attributes' => ['value' => 'Set new password'],
]);
}
}
<?php
declare(strict_types=1);
namespace App\Forms\Password;
use Laminas\Form\Element\Password;
use Laminas\Form\Element\Submit;
use Laminas\InputFilter\InputFilterProviderInterface;
use Laminas\Validator\NotEmpty;
use Override;
/**
* Changes the password of someone who is signed in
*
* Whether the current password is right is for the handler or controller to decide.
*
* @api
*
* @extends AbstractNewPasswordForm<array<string, mixed>>
*/
final class ChangePasswordForm extends AbstractNewPasswordForm implements InputFilterProviderInterface
{
public const string CURRENT_REJECTED = 'Your current password is incorrect';
#[Override]
public function getInputFilterSpecification(): array
{
return [
'current_password' => [
'required' => true,
'validators' => [
[
'name' => NotEmpty::class,
'options' => ['messages' => [NotEmpty::IS_EMPTY => 'Enter your current password']],
],
],
],
];
}
#[Override]
public function init(): void
{
parent::init();
$this->add([
'name' => 'current_password',
'type' => Password::class,
'options' => ['label' => 'Current password'],
'attributes' => ['id' => 'current_password', 'required' => true, 'autocomplete' => 'current-password'],
]);
$this->addNewPasswordFields('New password', 'Type your new password again');
$this->add([
'name' => 'save',
'type' => Submit::class,
'attributes' => ['value' => 'Change password'],
]);
}
public function rejectCurrentPassword(): void
{
$this->get('current_password')->setMessages([self::CURRENT_REJECTED]);
}
}
The last two share the input filter and base class from chapter 3:
<?php
declare(strict_types=1);
namespace App\Forms\Password;
use Laminas\InputFilter\InputFilter;
use Laminas\Validator\Identical;
use Laminas\Validator\NotEmpty;
use Laminas\Validator\StringLength;
use Override;
/**
* The rules for choosing a password, shared by every form that sets one
*
* Passwords are never filtered: every character counts. Fetch the filter from the input filter
* plugin manager, which calls init().
*
* @api
*
* @extends InputFilter<array<string, mixed>>
*/
final class NewPasswordInputFilter extends InputFilter
{
public const int MIN = 15;
public const int MAX = 128;
private const string FIELD_TO_MATCH = 'password';
#[Override]
public function init(): void
{
$this->add(
[
'required' => true,
'validators' => [
$this->notEmpty('Enter a password'),
[
'name' => StringLength::class,
'options' => [
'min' => self::MIN,
'max' => self::MAX,
'messages' => [
StringLength::TOO_SHORT => 'Your password must be at least %min% characters',
StringLength::TOO_LONG => 'Your password must be %max% characters or fewer',
],
],
],
],
],
'password',
);
$this->add(
[
'required' => true,
'validators' => [
$this->notEmpty('Enter your password again'),
[
'name' => Identical::class,
'options' => [
'token' => self::FIELD_TO_MATCH,
'messages' => [Identical::NOT_SAME => 'The passwords do not match'],
],
],
],
],
'password_confirm',
);
}
/** @return array{name: class-string<NotEmpty>, break_chain_on_failure: true, options: array{messages: array<string, string>}} */
private function notEmpty(string $message): array
{
return [
'name' => NotEmpty::class,
'break_chain_on_failure' => true,
'options' => ['messages' => [NotEmpty::IS_EMPTY => $message]],
];
}
}
<?php
declare(strict_types=1);
namespace App\Forms\Password;
use App\Forms\Csrf\AbstractCsrfProtectedForm;
use Laminas\Form\Element\Password;
use function sprintf;
/**
* Base class for forms in which someone chooses a password
*
* Subclasses call addNewPasswordFields() from init(). Their own rules still go in
* getInputFilterSpecification(), which is added to the shared ones.
*
* @api
*
* @template TData
*
* @extends AbstractCsrfProtectedForm<TData>
*/
abstract class AbstractNewPasswordForm extends AbstractCsrfProtectedForm
{
protected function addNewPasswordFields(string $label, string $confirmLabel): void
{
$hint = sprintf('At least %d characters. A few unrelated words work well.', NewPasswordInputFilter::MIN);
$inputFilters = $this->getFormFactory()->getInputFilterFactory()->getInputFilterManager();
$this->setInputFilter($inputFilters->get(NewPasswordInputFilter::class));
$this->add([
'name' => 'password',
'type' => Password::class,
'options' => ['label' => $label, 'hint' => $hint],
'attributes' => [
'id' => 'password',
'required' => true,
'minlength' => NewPasswordInputFilter::MIN,
'autocomplete' => 'new-password',
],
]);
$this->add([
'name' => 'password_confirm',
'type' => Password::class,
'options' => ['label' => $confirmLabel],
'attributes' => ['id' => 'password_confirm', 'required' => true, 'autocomplete' => 'new-password'],
]);
}
}
Checking a reset link needs your token storage, behind a one-method interface:
<?php
declare(strict_types=1);
namespace App\Forms\Password;
use SensitiveParameter;
/** @api */
interface ResetTokenLookupInterface
{
/**
* Returns the account a reset link belongs to, or null if the token is unknown, used or expired.
*/
public function accountFor(#[SensitiveParameter] string $token): ?string;
}
<?php
declare(strict_types=1);
namespace App\Forms\Password;
use Override;
use SensitiveParameter;
use function hash;
use function hash_equals;
/**
* Accepts a single hard-coded token, so that the example can be tried. Replace it with your token storage
*
* The token is "demo-reset-token". Only its hash is kept, as your storage should.
*
* @api
*/
final class DemoResetTokenLookup implements ResetTokenLookupInterface
{
private const string TOKEN_HASH = '49aa6134750dec3a09830296a87a731a519d46688b6617e336fca4c6c1eebedf';
#[Override]
public function accountFor(#[SensitiveParameter] string $token): ?string
{
return hash_equals(self::TOKEN_HASH, hash('sha256', $token)) ? 'sam@example.com' : null;
}
}
The change page also uses the credential check from chapter 2 and the signed-in person's profile from chapter 4:
<?php
declare(strict_types=1);
namespace App\Forms\Login;
use SensitiveParameter;
/** @api */
interface CredentialCheckerInterface
{
public function check(string $email, #[SensitiveParameter] string $password): bool;
}
<?php
declare(strict_types=1);
namespace App\Forms\Login;
use Override;
use SensitiveParameter;
use function password_verify;
use function strcasecmp;
/**
* Accepts a single hard-coded account, so that the example can be tried. Replace it with your user storage
*
* The password is "correct horse battery staple".
*
* @api
*/
final class DemoCredentialChecker implements CredentialCheckerInterface
{
private const string EMAIL = 'sam@example.com';
private const string PASSWORD_HASH = '$2y$12$.T9J2zh02yOnndJA31pmOOKKR6.Cv9a19ncH0PhbZuJ80RVdLrMLW';
#[Override]
public function check(string $email, #[SensitiveParameter] string $password): bool
{
// Always verify, so that response times do not reveal which accounts exist
$matches = password_verify($password, self::PASSWORD_HASH);
return $matches && 0 === strcasecmp($email, self::EMAIL);
}
}
<?php
declare(strict_types=1);
namespace App\Forms\Profile;
/** @api */
interface ProfileProviderInterface
{
/**
* The profile of the signed-in person.
*/
public function current(): Profile;
}
<?php
declare(strict_types=1);
namespace App\Forms\Profile;
use Override;
/**
* Returns the same made-up person every time. Replace it with your user storage
*
* @api
*/
final class DemoProfileProvider implements ProfileProviderInterface
{
#[Override]
public function current(): Profile
{
return new Profile(
name: 'Sam Taylor',
email: 'sam@example.com',
country: 'AU',
);
}
}
<?php
declare(strict_types=1);
namespace App\Forms\Profile;
/**
* What a person can change about their own account
*
* @api
*/
final class Profile
{
public function __construct(
public string $name,
public string $email,
public string $country,
public ?string $website = null,
public ?string $bio = null,
public string $contact = 'email',
) {}
}
None of the three forms needs a factory.
Mezzio
<?php
declare(strict_types=1);
namespace App\Handler;
use Laminas\Form\FormElementManager;
use Mezzio\Template\TemplateRendererInterface;
use Psr\Container\ContainerInterface;
/** @api */
final class ForgotPasswordHandlerFactory
{
public function __invoke(ContainerInterface $container): ForgotPasswordHandler
{
return new ForgotPasswordHandler(
$container->get(FormElementManager::class),
$container->get(TemplateRendererInterface::class),
);
}
}
<?php
declare(strict_types=1);
namespace App\Handler;
use App\Forms\Password\ResetTokenLookupInterface;
use Laminas\Form\FormElementManager;
use Mezzio\Template\TemplateRendererInterface;
use Psr\Container\ContainerInterface;
/** @api */
final class ResetPasswordHandlerFactory
{
public function __invoke(ContainerInterface $container): ResetPasswordHandler
{
return new ResetPasswordHandler(
$container->get(FormElementManager::class),
$container->get(TemplateRendererInterface::class),
$container->get(ResetTokenLookupInterface::class),
);
}
}
<?php
declare(strict_types=1);
namespace App\Handler;
use App\Forms\Login\CredentialCheckerInterface;
use App\Forms\Profile\ProfileProviderInterface;
use Laminas\Form\FormElementManager;
use Mezzio\Template\TemplateRendererInterface;
use Psr\Container\ContainerInterface;
/** @api */
final class ChangePasswordHandlerFactory
{
public function __invoke(ContainerInterface $container): ChangePasswordHandler
{
return new ChangePasswordHandler(
$container->get(FormElementManager::class),
$container->get(TemplateRendererInterface::class),
$container->get(CredentialCheckerInterface::class),
$container->get(ProfileProviderInterface::class),
);
}
}
<?php
declare(strict_types=1);
namespace App;
use App\Forms\Login\CredentialCheckerInterface;
use App\Forms\Login\DemoCredentialChecker;
use App\Forms\Password\DemoResetTokenLookup;
use App\Forms\Password\ResetTokenLookupInterface;
use App\Forms\Profile\DemoProfileProvider;
use App\Forms\Profile\ProfileProviderInterface;
use App\Handler\ChangePasswordHandler;
use App\Handler\ChangePasswordHandlerFactory;
use App\Handler\ForgotPasswordHandler;
use App\Handler\ForgotPasswordHandlerFactory;
use App\Handler\ResetPasswordHandler;
use App\Handler\ResetPasswordHandlerFactory;
use Laminas\ServiceManager\Factory\InvokableFactory;
/** @api */
final class PasswordConfigProvider
{
/** @return array<string, mixed> */
public function __invoke(): array
{
return [
'dependencies' => [
'aliases' => [
CredentialCheckerInterface::class => DemoCredentialChecker::class,
ProfileProviderInterface::class => DemoProfileProvider::class,
ResetTokenLookupInterface::class => DemoResetTokenLookup::class,
],
'factories' => [
DemoCredentialChecker::class => InvokableFactory::class,
DemoProfileProvider::class => InvokableFactory::class,
DemoResetTokenLookup::class => InvokableFactory::class,
ForgotPasswordHandler::class => ForgotPasswordHandlerFactory::class,
ResetPasswordHandler::class => ResetPasswordHandlerFactory::class,
ChangePasswordHandler::class => ChangePasswordHandlerFactory::class,
],
],
];
}
}
Add the provider to config/config.php, and register the routes:
<?php
declare(strict_types=1);
use App\Handler\ChangePasswordHandler;
use App\Handler\ForgotPasswordHandler;
use App\Handler\ResetPasswordHandler;
use Mezzio\Application;
return static function (Application $app): void {
$app->route('/forgot-password', ForgotPasswordHandler::class, ['GET', 'POST'], 'forgot-password');
$app->route('/reset-password', ResetPasswordHandler::class, ['GET', 'POST'], 'reset-password');
$app->route('/change-password', ChangePasswordHandler::class, ['GET', 'POST'], 'change-password');
};
laminas-mvc
<?php
declare(strict_types=1);
namespace Application\Controller;
use App\Forms\Csrf\CsrfGuardInterface;
use Laminas\Form\FormElementManager;
use Psr\Container\ContainerInterface;
/** @api */
final class ForgotPasswordControllerFactory
{
public function __invoke(ContainerInterface $container): ForgotPasswordController
{
return new ForgotPasswordController(
$container->get(FormElementManager::class),
$container->get(CsrfGuardInterface::class),
);
}
}
<?php
declare(strict_types=1);
namespace Application\Controller;
use App\Forms\Csrf\CsrfGuardInterface;
use App\Forms\Password\ResetTokenLookupInterface;
use Laminas\Form\FormElementManager;
use Psr\Container\ContainerInterface;
/** @api */
final class ResetPasswordControllerFactory
{
public function __invoke(ContainerInterface $container): ResetPasswordController
{
return new ResetPasswordController(
$container->get(FormElementManager::class),
$container->get(CsrfGuardInterface::class),
$container->get(ResetTokenLookupInterface::class),
);
}
}
<?php
declare(strict_types=1);
namespace Application\Controller;
use App\Forms\Csrf\CsrfGuardInterface;
use App\Forms\Login\CredentialCheckerInterface;
use App\Forms\Profile\ProfileProviderInterface;
use Laminas\Form\FormElementManager;
use Psr\Container\ContainerInterface;
/** @api */
final class ChangePasswordControllerFactory
{
public function __invoke(ContainerInterface $container): ChangePasswordController
{
return new ChangePasswordController(
$container->get(FormElementManager::class),
$container->get(CsrfGuardInterface::class),
$container->get(CredentialCheckerInterface::class),
$container->get(ProfileProviderInterface::class),
);
}
}
Merge this file into your module configuration, as Module does in chapter 0:
<?php
declare(strict_types=1);
namespace Application;
use App\Forms\Login\CredentialCheckerInterface;
use App\Forms\Login\DemoCredentialChecker;
use App\Forms\Password\DemoResetTokenLookup;
use App\Forms\Password\ResetTokenLookupInterface;
use App\Forms\Profile\DemoProfileProvider;
use App\Forms\Profile\ProfileProviderInterface;
use Laminas\Router\Http\Literal;
use Laminas\ServiceManager\Factory\InvokableFactory;
return [
'router' => [
'routes' => [
'forgot-password' => [
'type' => Literal::class,
'options' => [
'route' => '/forgot-password',
'defaults' => ['controller' => Controller\ForgotPasswordController::class, 'action' => 'form'],
],
],
'reset-password' => [
'type' => Literal::class,
'options' => [
'route' => '/reset-password',
'defaults' => ['controller' => Controller\ResetPasswordController::class, 'action' => 'form'],
],
],
'change-password' => [
'type' => Literal::class,
'options' => [
'route' => '/change-password',
'defaults' => ['controller' => Controller\ChangePasswordController::class, 'action' => 'form'],
],
],
],
],
'controllers' => [
'factories' => [
Controller\ForgotPasswordController::class => Controller\ForgotPasswordControllerFactory::class,
Controller\ResetPasswordController::class => Controller\ResetPasswordControllerFactory::class,
Controller\ChangePasswordController::class => Controller\ChangePasswordControllerFactory::class,
],
],
'service_manager' => [
'aliases' => [
CredentialCheckerInterface::class => DemoCredentialChecker::class,
ProfileProviderInterface::class => DemoProfileProvider::class,
ResetTokenLookupInterface::class => DemoResetTokenLookup::class,
],
'factories' => [
DemoCredentialChecker::class => InvokableFactory::class,
DemoProfileProvider::class => InvokableFactory::class,
DemoResetTokenLookup::class => InvokableFactory::class,
],
],
'view_manager' => [
'template_map' => [
'forms::forgot-password' =>
__DIR__ . '/../../../vendor/laminas-howto/forms-shared/templates/forgot-password.phtml',
'forms::reset-password' =>
__DIR__ . '/../../../vendor/laminas-howto/forms-shared/templates/reset-password.phtml',
'forms::reset-expired' =>
__DIR__ . '/../../../vendor/laminas-howto/forms-shared/templates/reset-expired.phtml',
'forms::change-password' =>
__DIR__ . '/../../../vendor/laminas-howto/forms-shared/templates/change-password.phtml',
],
],
];
A successful reset sends people to the sign-in page from chapter 2, which shows the confirmation.
<?php
declare(strict_types=1);
/**
* @var Laminas\View\Renderer\PhpRenderer $this
* @var App\Forms\Password\ForgotPasswordForm $form
* @var string|null $status
*/
$form->prepare();
$this->headTitle($form->getMessages() === [] ? 'Reset your password' : 'Error: Reset your password', 'SET');
?>
<?= $this->partial('forms::error-summary', ['form' => $form]) ?>
<h1>Reset your password</h1>
<p>We will email you a link for choosing a new password.</p>
<?php if ($status !== null): ?>
<p role="status" tabindex="-1" autofocus><?= $this->escapeHtml($status) ?></p>
<?php endif; ?>
<?= $this->form()->openTag($form) ?>
<?= $this->formElement($form->get('csrf')) ?>
<?= $this->partial('forms::field', ['element' => $form->get('email')]) ?>
<?= $this->formElement($form->get('send')) ?>
<?= $this->form()->closeTag() ?>
<?php
declare(strict_types=1);
/**
* @var Laminas\View\Renderer\PhpRenderer $this
* @var App\Forms\Password\ResetPasswordForm $form
*/
$form->prepare();
$this->headTitle($form->getMessages() === [] ? 'Choose a new password' : 'Error: Choose a new password', 'SET');
?>
<?= $this->partial('forms::error-summary', ['form' => $form]) ?>
<h1>Choose a new password</h1>
<?= $this->form()->openTag($form) ?>
<?= $this->formElement($form->get('csrf')) ?>
<?= $this->partial('forms::field', ['element' => $form->get('password')]) ?>
<?= $this->partial('forms::field', ['element' => $form->get('password_confirm')]) ?>
<?= $this->formElement($form->get('save')) ?>
<?= $this->form()->closeTag() ?>
Shown instead of the form when the link is wrong, used or out of date:
<?php
declare(strict_types=1);
/** @var Laminas\View\Renderer\PhpRenderer $this */
$this->headTitle('This link no longer works', 'SET');
?>
<h1>This link no longer works</h1>
<p>Reset links work once, and only for a short time.</p>
<p><a href="/forgot-password">Request a new link</a></p>
<?php
declare(strict_types=1);
/**
* @var Laminas\View\Renderer\PhpRenderer $this
* @var App\Forms\Password\ChangePasswordForm $form
* @var string|null $status
*/
$form->prepare();
$this->headTitle($form->getMessages() === [] ? 'Change your password' : 'Error: Change your password', 'SET');
?>
<?= $this->partial('forms::error-summary', ['form' => $form]) ?>
<h1>Change your password</h1>
<?php if ($status !== null): ?>
<p role="status" tabindex="-1" autofocus><?= $this->escapeHtml($status) ?></p>
<?php endif; ?>
<?= $this->form()->openTag($form) ?>
<?= $this->formElement($form->get('csrf')) ?>
<?= $this->partial('forms::field', ['element' => $form->get('current_password')]) ?>
<?= $this->partial('forms::field', ['element' => $form->get('password')]) ?>
<?= $this->partial('forms::field', ['element' => $form->get('password_confirm')]) ?>
<?= $this->formElement($form->get('save')) ?>
<?= $this->form()->closeTag() ?>
<?php
declare(strict_types=1);
namespace App\Handler;
use App\Csrf\MezzioCsrfGuard;
use App\Forms\Password\ForgotPasswordForm;
use Laminas\Diactoros\Response\HtmlResponse;
use Laminas\Diactoros\Response\RedirectResponse;
use Laminas\Form\FormElementManager;
use Mezzio\Csrf\CsrfGuardInterface;
use Mezzio\Csrf\CsrfMiddleware;
use Mezzio\Flash\FlashMessageMiddleware;
use Mezzio\Flash\FlashMessagesInterface;
use Mezzio\Template\TemplateRendererInterface;
use Override;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/** @api */
final readonly class ForgotPasswordHandler implements RequestHandlerInterface
{
public function __construct(
private FormElementManager $forms,
private TemplateRendererInterface $renderer,
) {}
#[Override]
public function handle(ServerRequestInterface $request): ResponseInterface
{
/** @var CsrfGuardInterface $guard */
$guard = $request->getAttribute(CsrfMiddleware::GUARD_ATTRIBUTE);
/** @var FlashMessagesInterface $flash */
$flash = $request->getAttribute(FlashMessageMiddleware::FLASH_ATTRIBUTE);
$form = $this->forms->get(ForgotPasswordForm::class);
$form->setCsrfGuard(new MezzioCsrfGuard($guard));
if ($request->getMethod() === 'POST') {
/** @var array<string, mixed> $post */
$post = $request->getParsedBody();
$form->setData($post);
if ($form->isValid()) {
// Limit requests here, per address and per IP address
// Queue the lookup and the email here, so that every address takes the same time to answer
$flash->flash(
'status',
'If an account uses that address, we have sent it a link for choosing a new password.',
);
return new RedirectResponse('/forgot-password', 303);
}
}
return new HtmlResponse($this->renderer->render('forms::forgot-password', [
'form' => $form,
'status' => $flash->getFlash('status'),
]));
}
}
<?php
declare(strict_types=1);
namespace App\Handler;
use App\Csrf\MezzioCsrfGuard;
use App\Forms\Password\ResetPasswordForm;
use App\Forms\Password\ResetTokenLookupInterface;
use Laminas\Diactoros\Response\HtmlResponse;
use Laminas\Diactoros\Response\RedirectResponse;
use Laminas\Form\FormElementManager;
use Mezzio\Csrf\CsrfGuardInterface;
use Mezzio\Csrf\CsrfMiddleware;
use Mezzio\Flash\FlashMessageMiddleware;
use Mezzio\Flash\FlashMessagesInterface;
use Mezzio\Template\TemplateRendererInterface;
use Override;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use function is_string;
/** @api */
final readonly class ResetPasswordHandler implements RequestHandlerInterface
{
public function __construct(
private FormElementManager $forms,
private TemplateRendererInterface $renderer,
private ResetTokenLookupInterface $tokens,
) {}
#[Override]
public function handle(ServerRequestInterface $request): ResponseInterface
{
// The token is in the address, so stop browsers passing it on to other pages
$headers = ['Referrer-Policy' => 'no-referrer'];
/** @var mixed $token */
$token = $request->getQueryParams()['token'] ?? null;
$account = is_string($token) ? $this->tokens->accountFor($token) : null;
if (null === $account) {
return new HtmlResponse($this->renderer->render('forms::reset-expired'), 400, $headers);
}
/** @var CsrfGuardInterface $guard */
$guard = $request->getAttribute(CsrfMiddleware::GUARD_ATTRIBUTE);
/** @var FlashMessagesInterface $flash */
$flash = $request->getAttribute(FlashMessageMiddleware::FLASH_ATTRIBUTE);
$form = $this->forms->get(ResetPasswordForm::class);
$form->setCsrfGuard(new MezzioCsrfGuard($guard));
if ($request->getMethod() === 'POST') {
/** @var array<string, mixed> $post */
$post = $request->getParsedBody();
$form->setData($post);
if ($form->isValid()) {
// Hash and save the password for $account here, then cancel this token and any others
// End the account's other sessions and email it to say the password has changed
$flash->flash('status', 'Your password has been changed. Sign in with your new password.');
return new RedirectResponse('/login', 303, $headers);
}
}
return new HtmlResponse($this->renderer->render('forms::reset-password', ['form' => $form]), 200, $headers);
}
}
<?php
declare(strict_types=1);
namespace App\Handler;
use App\Csrf\MezzioCsrfGuard;
use App\Forms\Login\CredentialCheckerInterface;
use App\Forms\Password\ChangePasswordForm;
use App\Forms\Profile\ProfileProviderInterface;
use Laminas\Diactoros\Response\HtmlResponse;
use Laminas\Diactoros\Response\RedirectResponse;
use Laminas\Form\FormElementManager;
use Mezzio\Csrf\CsrfGuardInterface;
use Mezzio\Csrf\CsrfMiddleware;
use Mezzio\Flash\FlashMessageMiddleware;
use Mezzio\Flash\FlashMessagesInterface;
use Mezzio\Template\TemplateRendererInterface;
use Override;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/** @api */
final readonly class ChangePasswordHandler implements RequestHandlerInterface
{
public function __construct(
private FormElementManager $forms,
private TemplateRendererInterface $renderer,
private CredentialCheckerInterface $credentials,
private ProfileProviderInterface $profiles,
) {}
#[Override]
public function handle(ServerRequestInterface $request): ResponseInterface
{
// Require a signed-in user before going any further
/** @var CsrfGuardInterface $guard */
$guard = $request->getAttribute(CsrfMiddleware::GUARD_ATTRIBUTE);
/** @var FlashMessagesInterface $flash */
$flash = $request->getAttribute(FlashMessageMiddleware::FLASH_ATTRIBUTE);
$form = $this->forms->get(ChangePasswordForm::class);
$form->setCsrfGuard(new MezzioCsrfGuard($guard));
if ($request->getMethod() === 'POST') {
/** @var array<string, mixed> $post */
$post = $request->getParsedBody();
$form->setData($post);
if ($form->isValid()) {
/** @var array{current_password: string, password: string} $data */
$data = $form->getData();
// Limit repeated attempts here
if ($this->credentials->check($this->profiles->current()->email, $data['current_password'])) {
// Hash and save $data['password'] here, regenerate the session ID and end other sessions
$flash->flash('status', 'Your password has been changed.');
return new RedirectResponse('/change-password', 303);
}
$form->rejectCurrentPassword();
}
}
return new HtmlResponse($this->renderer->render('forms::change-password', [
'form' => $form,
'status' => $flash->getFlash('status'),
]));
}
}
<?php
declare(strict_types=1);
namespace Application\Controller;
use App\Forms\Csrf\CsrfGuardInterface;
use App\Forms\Password\ForgotPasswordForm;
use Laminas\Form\FormElementManager;
use Laminas\Http\Request;
use Laminas\Http\Response;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Mvc\Plugin\FlashMessenger\FlashMessenger;
use Laminas\Stdlib\Parameters;
use Laminas\View\Model\ViewModel;
/** @api */
final class ForgotPasswordController extends AbstractActionController
{
public function __construct(
private readonly FormElementManager $forms,
private readonly CsrfGuardInterface $guard,
) {}
public function formAction(): Response|ViewModel
{
$form = $this->forms->get(ForgotPasswordForm::class);
$form->setCsrfGuard($this->guard);
/** @var Request $request */
$request = $this->getRequest();
/** @var FlashMessenger $flash */
$flash = $this->plugin('flashMessenger');
if ($request->isPost()) {
/** @var Parameters $post */
$post = $request->getPost();
$form->setData($post->toArray());
if ($form->isValid()) {
// Limit requests here, per address and per IP address
// Queue the lookup and the email here, so that every address takes the same time to answer
$flash->addSuccessMessage(
'If an account uses that address, we have sent it a link for choosing a new password.',
);
return $this->redirect()->toRoute('forgot-password')->setStatusCode(303);
}
}
$view = new ViewModel([
'form' => $form,
'status' => $flash->getSuccessMessages()[0] ?? null,
]);
return $view->setTemplate('forms::forgot-password');
}
}
<?php
declare(strict_types=1);
namespace Application\Controller;
use App\Forms\Csrf\CsrfGuardInterface;
use App\Forms\Password\ResetPasswordForm;
use App\Forms\Password\ResetTokenLookupInterface;
use Laminas\Form\FormElementManager;
use Laminas\Http\Request;
use Laminas\Http\Response;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Mvc\Controller\Plugin\Params;
use Laminas\Mvc\Plugin\FlashMessenger\FlashMessenger;
use Laminas\Stdlib\Parameters;
use Laminas\View\Model\ViewModel;
use function is_string;
/** @api */
final class ResetPasswordController extends AbstractActionController
{
public function __construct(
private readonly FormElementManager $forms,
private readonly CsrfGuardInterface $guard,
private readonly ResetTokenLookupInterface $tokens,
) {}
public function formAction(): Response|ViewModel
{
/** @var Response $response */
$response = $this->getResponse();
// The token is in the address, so stop browsers passing it on to other pages
$response->getHeaders()->addHeaderLine('Referrer-Policy', 'no-referrer');
/** @var Params $params */
$params = $this->plugin('params');
/** @var mixed $token */
$token = $params->fromQuery('token');
$account = is_string($token) ? $this->tokens->accountFor($token) : null;
if (null === $account) {
$response->setStatusCode(400);
return new ViewModel()->setTemplate('forms::reset-expired');
}
$form = $this->forms->get(ResetPasswordForm::class);
$form->setCsrfGuard($this->guard);
/** @var Request $request */
$request = $this->getRequest();
/** @var FlashMessenger $flash */
$flash = $this->plugin('flashMessenger');
if ($request->isPost()) {
/** @var Parameters $post */
$post = $request->getPost();
$form->setData($post->toArray());
if ($form->isValid()) {
// Hash and save the password for $account here, then cancel this token and any others
// End the account's other sessions and email it to say the password has changed
$flash->addSuccessMessage('Your password has been changed. Sign in with your new password.');
return $this->redirect()->toRoute('login')->setStatusCode(303);
}
}
return new ViewModel(['form' => $form])->setTemplate('forms::reset-password');
}
}
<?php
declare(strict_types=1);
namespace Application\Controller;
use App\Forms\Csrf\CsrfGuardInterface;
use App\Forms\Login\CredentialCheckerInterface;
use App\Forms\Password\ChangePasswordForm;
use App\Forms\Profile\ProfileProviderInterface;
use Laminas\Form\FormElementManager;
use Laminas\Http\Request;
use Laminas\Http\Response;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Mvc\Plugin\FlashMessenger\FlashMessenger;
use Laminas\Stdlib\Parameters;
use Laminas\View\Model\ViewModel;
/** @api */
final class ChangePasswordController extends AbstractActionController
{
public function __construct(
private readonly FormElementManager $forms,
private readonly CsrfGuardInterface $guard,
private readonly CredentialCheckerInterface $credentials,
private readonly ProfileProviderInterface $profiles,
) {}
public function formAction(): Response|ViewModel
{
// Require a signed-in user before going any further
$form = $this->forms->get(ChangePasswordForm::class);
$form->setCsrfGuard($this->guard);
/** @var Request $request */
$request = $this->getRequest();
/** @var FlashMessenger $flash */
$flash = $this->plugin('flashMessenger');
if ($request->isPost()) {
/** @var Parameters $post */
$post = $request->getPost();
$form->setData($post->toArray());
if ($form->isValid()) {
/** @var array{current_password: string, password: string} $data */
$data = $form->getData();
// Limit repeated attempts here
if ($this->credentials->check($this->profiles->current()->email, $data['current_password'])) {
// Hash and save $data['password'] here, regenerate the session ID and end other sessions
$flash->addSuccessMessage('Your password has been changed.');
return $this->redirect()->toRoute('change-password')->setStatusCode(303);
}
$form->rejectCurrentPassword();
}
}
$view = new ViewModel([
'form' => $form,
'status' => $flash->getSuccessMessages()[0] ?? null,
]);
return $view->setTemplate('forms::change-password');
}
}
How it works
Say the same thing to everyone. The forgot form checks only the format of the address, and every valid address gets the same answer. The time taken must match too, so queue the lookup and the email rather than doing them while the visitor waits.
The token is not a form field. It stays in the address. The form sets no address to submit to, so the browser posts back to the current one, token included. The handler or controller checks it before showing the form and again before accepting a password.
Keep the token to yourself. An address can be passed to other sites in the Referer header. Referrer-Policy: no-referrer stops that.
A bad link gets its own page. Showing a password form that can never succeed wastes the visitor's effort. The page answers with status 400 and offers a new link.
One set of password rules. Registration, reset and change all use NewPasswordInputFilter, so the policy changes in one place. ChangePasswordForm adds the rule for the current password through getInputFilterSpecification().
The current password is not judged. It has no length rule or filter: it may predate your current policy. A wrong one is reported on its field, in the same way chapter 2 reports a failed sign-in.
Password managers need to know which is which. current-password fills the old one, and new-password offers to generate and save a new one. Password fields always come back empty.
Before you use this for real
These follow the OWASP Forgot Password Cheat Sheet.
- Create tokens with
bin2hex(random_bytes(32)). Store only a hash, tied to one account, with an expiry time. - Make each token work once, and cancel any others when the password changes.
- Build the link from a configured site address, never from the request's
Hostheader. Use HTTPS. - Limit reset requests per account and per IP address. Do not lock the account.
- Keep tokens out of your server logs, and do not load third-party scripts on the reset page.
- Do not sign the person in after a reset. Email them to say the password changed, and end their other sessions.
- Require a signed-in user on the change page, and limit attempts at the current password.
- Hash passwords and reject breached ones, as in chapter 3.
Further opportunities
None of these are built or tested here. Add the ones your site needs.
| Opportunity | Where | How |
|---|---|---|
| Help password managers name the account | Reset and change templates | Add a read-only field with autocomplete="username" showing the address |
| Refuse the old password as the new one | Handler or controller | Check the new password against the stored hash |
| Remove the token from the address | Reset handler or controller | On first visit, move it into the session and redirect to the plain address |
| Ask for a second factor | Between the link and the form | Require a code from an authenticator app before accepting a new password |
| Offer a way out | The email | Include a "This wasn't me" link that cancels the token |
| Ask again before sensitive actions | Middleware or a controller plugin | Require the current password if it was last entered long ago |
Common mistakes
- Saying "no account uses that address".
- Checking the token only when the page is first shown.
- Putting the account's ID or email in the form, and trusting what comes back.
- Setting an
actionon the reset form that leaves out the token. - Adding a length rule to the current password.
- Creating the input filter with
new, which leaves it without rules.