Using Passwordless Authentication with a one-time code via email on SPA

With the email connection, the user is requested to enter their email address. Auth0 then sends an email to that address containing a one-time code.

Once the user enters this code into your application, a new user will be created in the email connection. The user is then authenticated by Auth0.

If the email address matches an existing user, Auth0 just authenticates the user:

Setup

Configure an email provider

By default, Auth0 sends the email from its own SMTP provider. Auth0's built-in email infrastructure should be used for testing level emails only. You can configure your own email provider to better monitor and troubleshoot the email service as well as be able to fully customize the emails.

You will need to use your own email provider to be able to modify the From, Subject and Body of Passwordless emails.

Configure the connection

In the Dashboard, on the Email page, under Connections > Passwordless, you can configure the contents and behavior of the email.

Multi-Language Support

The Message area supports usage of multiple languages.

By making a call to the /passwordless/start authentication endpoint, you can set the value of an 'x-request-language' header to the language of your choice. If the value of this header is not set, the language will be extracted from the value in the 'accept-language' header that is automatically set by the browser.

The Message area accepts Liquid syntax. You can use this syntax, combined with exposed parameter values, to programmatically construct elements of the message. For example, you can reference the request_language parameter to change the language of the message:

{% if request_language contains 'dutch' %}
   Hier is uw verificatie code: {{ code }}
{% endif %}

{% if request_language contains 'fr-FR' %}
   Ceci est votre code: {{ code }}
{% endif %}

The following parameters are available when defining the template:

Exposed Parameter Description
code the password to use
link the magic link
application.name the name of the application name where the user is signing up
request_language the requested language for the message content
operation equals change_email when the template is triggered by an update to a user's email via the API, otherwise null

Configure CORS

For security purposes, you must add your app's origin URL to the list of Allowed Origins (CORS) in your app's Settings Section of the Dashboard, unless this origin URL has been already added to the Allowed callback URLs list.

Implementation

Use Lock (the Auth0 UI widget)

Lock with Passwordless Mode is a professional-looking dialog that allows users to log in after receiving a one-time password via email or text message.

After installing Lock (version 11.2.0 or later), you must initialize it with your Client Id and domain. You can find this information in the Dashboard on your application settings page.

Then you can trigger the login with the following code:

<script src="https://cdn.auth0.com/js/lock/11.6.1/lock.min.js"></script>
<script type="text/javascript">
   var lock = new Auth0LockPasswordless('YOUR_CLIENT_ID', 'YOUR_AUTH0_DOMAIN', {
    allowedConnections: ['email'],           // Should match the Email connection name, it defaults to 'email'     
    passwordlessMethod: 'code',              // If not specified, defaults to 'code'
    auth: {
      redirectUrl: 'https://YOUR_APP/callback',
      responseType: 'token id_token'
    }
  });

  lock.on('authenticated', function(authResult) {
      localStorage.setItem('id_token', authResult.idToken);
      localStorage.setItem('access_token', authResult.accessToken);
  });

  function login() {
      lock.show();
  }
</script>
<a href="javascript:login()">Login</a>

First, this will open a dialog that asks the user for their email address:

Then Auth0 will send an email to the user containing the one-time code:

Lock will ask for the code that has been emailed to the provided address. The code can then be used as a one-time password to log in.

Once the user enters the code received by email, Lock will authenticate them and call the callback function where the ID Token and profile will be available.

Use your own UI

Sample Project

Download a sample project specific to this tutorial configured with your Auth0 API Keys.

You can perform passwordless authentication in your SPA with your own custom UI using the Auth0 JavaScript SDK.

Construct a new instance of the Auth0 client as follows:

<script src="https://cdn.auth0.com/js/auth0/9.5.1/auth0.min.js"></script>
<script type="text/javascript">
  var webAuth = new auth0.WebAuth({
    domain:       'YOUR_AUTH0_DOMAIN',
    clientID:     'YOUR_CLIENT_ID',
    redirectUri: 'https://YOUR_APP/callback'
  });
</script>

Be sure to provide a redirectUri and to set the responseType: 'token'.

You must provide a way for the user to enter a address to which the email will be sent. Then you can begin the passwordless authentication as follows (assuming the name of your form input as input.email):

function sendEmail(){
  var email = $('input.email').val();

  webAuth.passwordlessStart({
    connection: 'email',
    send: 'code',
    email: email
  }, function (err,res) {
    if (err) {
      // Handle error
    }
    // Hide the input and show the code entry screen
    $('.enter-email').hide();
    $('.enter-code').show();
  });
}

This will send an email to the provided address. The user must now enter the code they received into your custom UI. Then you can continue with the login as follows (assuming the name of your form inputs as input.email and input.code):

function login(){
  var email = $('input.email').val();
  var code = $('input.code').val();

  webAuth.passwordlessVerify({
    connection: 'email',
    email: email,
    verificationCode: code
  }, function (err,res) {
    if (err) {
      // Handle error
    }
    // If successful, save the user's token and proceed
  });
};

The passwordlessVerify method will verify the Passwordless transaction, then redirect the user back to the redirectUri that was set. You will then need to parse the URL hash in order to acquire the token, and then call the client.userInfo method to acquire your user's information, as in the following example:

$(document).ready(function() {
  if(window.location.hash){
    webAuth.parseHash(window.location.hash, function(err, authResult) {
      if (err) {
        return console.log(err);
      } else if (authResult){
        localStorage.setItem('accessToken', authResult.accessToken);
        webAuth.client.userInfo(authResult.accessToken, function(err, user) {
          if (err){
            console.log('err',err);
            alert('There was an error retrieving your profile: ' + err.message);
          } else {
            // Hide the login UI, show a user profile element with name and image
            $('.login-box').hide();
            $('.logged-in-box').show();
            localStorage.setItem('user', user);
            $('.nickname').text(user.nickname);
            $('.avatar').attr('src', user.picture);
          }
        });
      }
    });
  }
});

Check out the Auth0.js SDK reference documentation for more information.