One time logins

There’s often a need to give users a one-time use ‘magic’ URL to login to an application without a password.

URLs like this could be added to invitation emails for new users so they can get started straight away.

Enable the SingleUseAuthenticator

The bundle includes a SingleUseAuthenticator, with the service name perform_user.auth.single_use, to add to your firewall configuration.

Here’s an example for a firewall also using form logins:

firewalls:
    main:
        pattern: ^/
+       simple_preauth:
+           authenticator: perform_user.auth.single_use
        form_login:
            login_path: perform_user_login
            check_path: perform_user_login
            csrf_token_generator: security.csrf.token_manager
        logout:
            path: perform_user_logout
            target: /
        anonymous: true

Users will now be able to login with a signed URL.

Generate a signed URL

Use the generateUrl() method of the authenticator, passing in the user and the destination URL.

You can then use this URL in welcome emails, administration areas, or wherever else you require it.

<?php

/* @var Symfony\Component\Routing\Generator\UrlGeneratorInterface $urlGenerator */
$targetUrl = $urlGenerator->generate('app_index', [], UrlGeneratorInterface::ABSOLUTE_URL);
// https://example.com/

/* @var Perform\UserBundle\Entity\User $user */
/* @var Perform\UserBundle\Security\SingleUseAuthenticator $auth */
$signedUrl = $auth->generateUrl($user, $targetUrl);
// https://example.com/?_a=0000&_t=0000&_hash=0000

Note

You’ll likely want to use the router to generate the target URL, making sure the hostname is included, not just the path.

Requiring a password reset after use

Make sure the passwordExpiresAt property of the user is in the past. See Resetting passwords.

Differences between one-time logins and password reset tokens

You may wonder why there are two URL-based mechanisms to gain access to an account without the password; reset tokens and one-time logins. However, they both have distinct uses that necessitates they both exist:

  • Storage - Reset tokens are saved in the database, one-time logins are not.
  • Expiry - Reset tokens have an individual expiry date, one-time logins expire whenever a user logs in.
  • Login - Reset tokens don’t log the user in, one-time logins do.
  • Purpose - Reset tokens are designed to be generated by the user and emailed to them, one-time logins are often used by administrators to access other accounts or to send invitations to new users.

Note

Both reset tokens and one-time logins use the UriSigner service to sign the generated URLs. If the framework.secret configuration value changes, all URLs will be invalidated.

Read more about the implications of changing the secret here.