Force Users to Verify their Accounts Before Logging In

Overview

Due to certain requirements or use cases, users might need to verify their email before logging into one of your applications. This article explains how they can receive a verification email whenever they try to log in without a verified account.

They can also be redirected to a custom page that includes instructions regarding their need to verify their email.

Applies To

  • Actions
  • Account Verification

Solution

A custom approach using actions can be implemented. Here’s a quick example of such code:

exports.onExecutePostLogin = async (event, api) => {
  const ManagementClient = require('auth0').ManagementClient;
  const management = new ManagementClient({
    domain: event.secrets.domain,
    clientId: event.secrets.clientId,
    clientSecret: event.secrets.clientSecret
  });
  console.log(event.stats.logins_count);
  // check if it's the first time the user logs in - if so, do not send a second verification email
  if(event.stats.logins_count===1){
    return;
  }
  const verified = event.user.email_verified;

  // slicing off the 'auth0|' prefix of the user_id here
  const userIdWithoutAuth0 = event.user.user_id.slice(6);

  const params = {
    client_id: event.client.client_id,
    user_id: event.user.user_id
  };

  if (!verified) {
    let client = event.client.client_id;
    let logout_url = 'https://your_tenant_domain.us.auth0.com/v2/logout?client_id=';
    api.redirect.sendUserTo(logout_url + client, {
      query: { returnTo: "your_custom_page_URL" },
    });
    management.jobs.verifyEmail(params, function (err) {
      if (err) {
        console.log(err)
      }
    });
  }
};

Please consider adding “auth0” as a dependency before testing this out.

The domain, clientId, and clientSecret should also be added as secrets. In addition, the clientId and clientSecret need to correspond to an M2M application from the tenant. This can be the default “API Explorer Application”, for example.

The “your_custom_page_URL” URL should also be added to the Allowed Callback URL list for that specific application.