Block Login from IP Address and Email Domain

Problem statement

This article will cover how to block login from IP addresses and email domains. This control must be applied to only one specific email domain. Logins from other email domains should not be blocked.

Solution

This capability can be implemented using a Login/Post-Login flow within Actions.

For guidance on how to create an Action, refer to Write Your First Action.

  1. Login to the Auth0 dashboard.
  2. Navigate to Actions > Library > Login.
  3. To the right of the next screen, in the Add Action block, click on Custom.

  1. Click Create Action to display a dialogue box.
  2. In the box, assign a Name, select a Trigger (Login/Post Login) and the preferred Node.js runtime.
  3. Click Create to open the online code editor for the Action.

Copy and paste the following sample code into the online code editor and use it as a starting point for developing an Action that meets the specific requirements of the use case.

exports.onExecutePostLogin = async (event, api) => {
  const ipaddr = require("ipaddr.js");
  const email = event.user.email;
  const currentIp = ipaddr.parse(event.request.ip);
  
  // IP range to prohibit (e.g. 192.168.1.128 to 192.168.1.191 )
  const ipRange = "192.168.1.134/26";
  
  // if the current IP address is in the prohibited range, block access
  // and print an error message
  if (email.endsWith("@example.com") && currentIp.match(ipaddr.parseCIDR(ipRange))) {
    api.access.deny("Login from this IP address is prohibited");
  } ;
};

Related References