Force New User to Change Password on First Login

Overview

This article provides steps to force a new user to reset their password upon their first login attempt. This requirement can arise from a need to enhance security or when user accounts are pre-created.

Applies To
  • Change Password
  • First Login
  • Actions
Solution

The following options are available to achieve this functionality:

 

Option 1: Utilize a Post-Login Action and a Post-Change Password Action

This option uses a combination of two actions in Auth0: a post-login action and a post-change password action.

  1. Post-Login Action: This action checks the logic for when the user is allowed to access the application based on the needsPasswordReset flag.

    exports.onExecutePostLogin = async (event, api) => {
      // Import the axios library to handle the POST request to the Auth0 Management API
      const axios = require("axios").default;
    
      // Retrieve the total number of times this user has logged in
      const loginCount = event.stats.logins_count;
    
      /**
       * Helper function to trigger the "Change Password" flow via Auth0's Authentication API.
       * This sends an automated password reset email to the user.
       */
      const sendPasswordResetEmail = async () => {
        const options = {
          method: 'POST',
          url: 'https://auth0-domain/dbconnections/change_password',
          headers: { 'content-type': 'application/json' },
          data: {
            email: event.user.email,
            connection: event.connection.name, // The database connection the user belongs to
            client_id: event.client.client_id  // The application ID
          },
        };
    
        try {
          console.log('Sending email resetting password...');
          // We use 'await' to ensure the request completes before the Action finishes
          const response = await axios.request(options);
          console.log("Response: ", response.data);
        } catch (error) {
          // Log the error for debugging in the Auth0 Dashboard
          console.error("Axios error:", error);
        }
      };
    
      // LOGIC: If this is the user's very first login
      if (loginCount === 1) {
        // Flag the user in app_metadata so we know they are in the "reset required" state
        api.user.setAppMetadata("needsPasswordReset", true);
        
        // Trigger the reset email immediately
        await sendPasswordResetEmail();
    
      } else {
        // LOGIC: For any subsequent login (2, 3, etc.), check if they still have the flag
        // This handles cases where they logged in again but haven't finished the reset yet
        if (event.user.app_metadata.needsPasswordReset === true) {
          await sendPasswordResetEmail();
        }
      }
    
      // PREPARE REDIRECT: Define the logout and return parameters
      const clientId = event.client.client_id;
      const logoutUrl = `https://auth0-domain/v2/logout?client_id=${clientId}`;
      
      /**
       * Important: Because we want to force the user to change their password BEFORE they 
       * can access the app, we log them out immediately and redirect them to a 
       * custom instructions page.
       */
      api.redirect.sendUserTo(logoutUrl, {
        query: { returnTo: "custom_page_with_instructions_URL" },
      });
    };
  2. Post-Change Password Action: This action uses the Management API to change the user's metadata flag value after they change their password, allowing them to login.

    // Post Change Password Action to update user metadata using the management api
    
    exports.onExecutePostChangePassword = async (event) => {
      const ManagementClient = require('auth0').ManagementClient;
      const management = new ManagementClient({
        domain: yourAuth0Domain,
        clientId: M2M_Client_ID,
        clientSecret: M2M_Client_Secret,
        scope: 'read:users update:users',
      });
      try {
        // Update the needsPasswordReset flag to false after password reset
        await management.updateAppMetadata( { needsPasswordReset: false });
      } catch (error) {
        console.error('An error occurred while updating user metadata:', error);
      }
    };

    Refer to the Using the Management API in Actions documentation for more details on using the Management API in Actions. This combination ensures new users are prompted to reset their passwords upon first login.

 

Option 2: Leverage the Forms Feature

This option uses the Forms feature. A basic example of this implementation is shown below:

Forms feature example

  1. Create a form with a step node to obtain the new password value from the user and a flow node to update the metadata with the new password.

    • Step Node Configuration: For example, the Field ID could be "password". This ID is used to pass the field value to the flow node.
      Field Settings - Step node
    • Flow Node Configuration: Modify the {{fields.ID}} placeholder in the Update a User request payload to match the Field ID from the step node (e.g., {{fields.password}}). 
      Flow Node configuration  
    • Add an If/then condition node immediately after the Update user node to verify the update success.If/Then Condition Node example  

      Configure the condition to check if the status code from the password update is greater than or equal to 400.

       

      In the TRUE path of the condition, add a Show error message node to stop the flow if the update is not successful.

      In the FALSE path, allow the flow to CONTINUE.

  2. Publish the form.

  3. Render Forms using Actions. Use the login count to determine if the user is new.

    exports.onExecutePostLogin = async (event, api) => {
      const FORM_ID = 'ENTER FORM ID HERE';
      const loginCount = event.stats.logins_count;
      if (loginCount === 1) {
        api.prompt.render(FORM_ID);
      }
    }
    exports.onContinuePostLogin = async (event, api) => {}

    After the password is changed, the user is logged in. Tenant logs will confirm the password change.

 

Option 3: Manual Password Reset Initiation via Email

This method involves creating user accounts with a random password and then initiating a password reset process.

  1. Create user accounts with a randomly generated password.
  2. Initiate the password reset for the user through one of the following methods:

This approach ensures that the user must:

  • Have access to the email address associated with their account.
  • Set their own password before their initial login.

Recommended content

No recommended content found...