@@ -256,6 +256,64 @@ You can customize the reset password bundle's behavior by updating the
256256``reset_password.yaml `` file. For more information on the configuration,
257257check out the `SymfonyCastsResetPasswordBundle `_ guide.
258258
259+ Injecting a Specific Password Hasher
260+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
261+
262+ In some cases, you may define a password hasher in your configuration that is
263+ not tied to a user class. For example, you might use a separate hasher for
264+ password recovery codes or API tokens.
265+
266+ With the following configuration:
267+
268+ .. code-block :: yaml
269+
270+ # config/packages/security.yaml
271+ security :
272+ password_hashers :
273+ recovery_code : ' auto'
274+
275+ firewalls :
276+ main :
277+ # ...
278+
279+ You can inject the ``recovery_code `` password hasher into any service. However,
280+ you can't rely on standard autowiring, as Symfony doesn't know which specific
281+ hasher to provide.
282+
283+ Instead, use the ``#[Target] `` attribute to explicitly request the hasher by
284+ its configuration key::
285+
286+ // src/Controller/HomepageController.php
287+ namespace App\Controller;
288+
289+ use Symfony\Component\DependencyInjection\Attribute\Target;
290+ use Symfony\Component\PasswordHasher\PasswordHasherInterface;
291+
292+ class HomepageController extends AbstractController
293+ {
294+ public function __construct(
295+ #[Target('recovery_code')]
296+ private readonly PasswordHasherInterface $passwordHasher,
297+ ) {
298+ }
299+
300+ #[Route('/')]
301+ public function index(): Response
302+ {
303+ $plaintextToken = 'some-secret-token';
304+
305+ // Note: use hash(), not hashPassword(), as we are not using a UserInterface object
306+ $hashedToken = $this->passwordHasher->hash($plaintextToken);
307+ }
308+ }
309+
310+ When injecting a specific hasher by its name, you should type-hint the generic
311+ :class: `Symfony\\ Component\\ PasswordHasher\\ PasswordHasherInterface `.
312+
313+ .. versionadded :: 7.4
314+
315+ The feature to inject specific password hashers was introduced in Symfony 7.4.
316+
259317.. _security-password-migration :
260318
261319Password Migration
0 commit comments