Navigation

Email/Password Authentication

MongoDB Stitch provides the option for your app end users to authenticate with their email address and password. In addition, Stitch provides functionality for confirming the email address of a newly registered user and resetting the password of a user who has forgotten theirs.

Note

The Email/Password authentication provider requires users to choose passwords between 6 and 128 characters long. When building your client UI, you may wish to add client-side validation for this rule. Stitch does not impose any additional password restrictions.

Enable and Configure Email/Password Authentication

To configure for email/password authentication,

  1. Click Users from the left-side navigation.

  2. Select the Providers tab.

  3. For Email/Password, click the Edit button.

  4. In the Email/Password settings:

    1. Switch the Provider Status toggle to enabled.

    2. Enter values for the following fields as appropriate:

      Field Description
      Email Confirmation URL

      Required. The base URL for the confirmation URL sent to users to confirm their email address. The confirmation URL is sent to the user via email and includes the query parameters token and tokenId. For the base URL, you must include the URL scheme, such as http or https. For example, https://myapp.example.com/foo/confirm.

      The confirmation script hosted at this URL must parse the token and tokenId and call the emailConfirm() function in the JavaScript SDK.

      Additionally, if you’d like the confirmation step to be handled within your mobile client application, you’ll need to configure your application to handle this link by using deep linking in Android, or universal links in iOS. Both the Android and iOS SDKs offer an emailConfirm function that can be used when handling this link.

      See Incorporate into a Client Application below for more detailed examples.

      Email Confirmation Subject

      Optional. The subject of the email sent to users to confirm their email address. Maximum length is 256 characters.

      For example, MyApp Email Address Confirmation

      If unspecified, MongoDB Stitch uses a default subject.

      Password Reset URL

      Required. The base URL for the password reset URL sent to users to reset their password. The reset URL is sent to the user via email and includes the query parameters token and tokenId. For the base URL, you must include the URL scheme, such as http or https. For example, https://myapp.example.com/reset-pwd-verify

      Similar to the email confirmation script, the password reset script at this link must parse the token and tokenId and call the passwordReset() function in the JavaScript SDK

      Additionally, the mobile SDKs offer a resetPassword() function if you would like to handle the link in your mobile client application.

      See Incorporate into a Client Application below.

      Reset Password Email Subject

      Optional. The subject of the email sent to users to reset their password. Maximum length is 256 characters.

      For example, MyApp Password Reset

      If unspecified, MongoDB Stitch uses a default subject.

    3. Click Save.

Incorporate into a Client Application

To incorporate email/password authentication into a web application, use the following code snippets:

Note

These code snippets are not meant to be a comprehensive step-by-step procedure.

  1. In your HTML file, include the MongoDB Stitch library .

    <script defer type="text/javascript" src="https://s3.amazonaws.com/stitch-sdks/js/library/v3/stable/stitch.min.js"></script>
    
  2. In your JavaScript file, include the code to build a StitchClient.

    See Initialize StitchClient for more details on initializing a StitchClient in your application.

  3. To register a user’s email and password, the StitchClient provides the register() method. This only needs to be called when a user is registering for the first time. Existing users can simply login with the login() method on the StitchClient.

    yourStitchClient.register('<user-email>', '<user-password>')
        .then(() => {
            console.log("Successfully sent account confirmation email!");
            /* code to direct user to check their email */
        })
        .catch(err => {
            console.log("Error registering new user:", err);
        });
    

    Upon successful registration, the user is sent a confirmation email with the confirmation link. The confirmation link includes token and tokenId query parameters.

    At this point in the registration flow for new users, you should direct users to check their email for a confirmation link.

    Note

    If the password does not meet the Stitch length requirements, the following error is returned:

    StitchError: password must be between 6 and 128 characters

  4. When the user clicks on the link, the confirmation script must parse the token and tokenId and pass to the emailConfirm() function.

    // ... logic to parse token and tokenId
    
    yourStitchClient.auth.provider('userpass').emailConfirm('<tokenid>', '<token>')
        .then(() => {
            console.log("Successfully confirmed email address!");
            /* code to direct user to log in with their newly confirmed account */
        })
        .catch(err => {
            console.log("Error confirming email address:", err);
        });
    

    Once the user email has been confirmed, the user can login with the registered email and password, at which time the user is created in MongoDB Stitch.

    Note

    The user is created upon the first login with the registered email and password; the email confirmation step does not create the user in MongoDB Stitch.

    This means that in the Users interface, you will not be able to view or delete a user who has confirmed their email address but not yet logged in for the first time.

  5. To login with a user’s email and password, the StitchClient provides the login() function.

    yourStitchClient.login('<user-email>', '<user-password>')
        .then(userId => {
            console.log("Successfully logged in as user", userId);
        })
        .catch(err => {
            console.log("Error logging in with email/password auth:", err);
        });
    

    This step authenticates the MongoDB Stitch client and begins a Stitch session.

  6. To send a user an email to reset their password, use the sendPasswordReset() function.

    yourStitchClient.auth.provider('userpass').sendPasswordReset('<user-email>')
        .then(() => {
            console.log("Successfully sent password reset link!");
        })
        .catch(err => {
            console.log("Error sending password reset link:", err);
        });
    

    The user will be sent an email with a password reset link. The reset link includes token and tokenId query parameters.

  7. To reset the password after the user clicks on the link, the reset password script must parse the token and tokenId and pass to the passwordReset() function along with the new password.

    yourStitchClient.auth.provider('userpass').passwordReset('<tokenid>', '<token>', '<new-password>')
        .then(() => {
            console.log("Successfully reset password!");
        })
        .catch(err => {
            console.log("Error resetting password:", err);
        });
    

To incorporate email/password authentication into an Android application, use the following code snippets:

Note

These code snippets are not meant to be a comprehensive step-by-step procedure.

  1. Import the MongoDB Stitch client and email/password provider.

    import com.mongodb.stitch.android.StitchClient;
    import com.mongodb.stitch.android.auth.emailpass.EmailPasswordAuthProvider;
    
  2. Include the code to instantiate a StitchClient.

    See Initialize StitchClient for more details on initializing a StitchClient in your application.

  3. To register a user’s email and password, the StitchClient provides the register() method. This only needs to be called when a user is registering for the first time. Existing users can simply login with the logInWithProvider() method on the StitchClient.

    yourStitchClient.register("<user-email>", "<user-password>").addOnCompleteListener(new OnCompleteListener<Boolean>() {
        @Override
        public void onComplete(@NonNull final Task<Boolean> task) {
            if (task.isSuccessful()) {
                Log.d("stitch", "Successfully sent account confirmation email");
                /* code to direct user to check their email */
            } else {
                Log.e("stitch", "Error registering new user:", task.getException());
            }
        }
    });
    

    Upon successful registration, the user is sent a confirmation email with the confirmation link. The confirmation link includes token and tokenId query parameters.

    At this point in the registration flow for new users, you should direct users to check their email for a confirmation link.

    Note

    If the password does not meet the Stitch length requirements, the following error is returned:

    StitchError: password must be between 6 and 128 characters

  4. When the user clicks on the link, there are two possible ways to handle the confirmation step.

    At a minimum, you should implement a statically-hosted confirmation script at the confirmation link using the JavaScript SDK. This script must parse the token and tokenId from the query parameters of the URL and pass it to the emailConfirm() function.

    // ... logic to parse token and tokenId
    
    yourStitchClient.auth.provider('userpass').emailConfirm('<tokenid>', '<token>');
        .then(() => {
            console.log("Successfully confirmed email address!");
            /* code to direct user to log in with their newly confirmed account */
        })
        .catch(err => {
            console.log("Error confirming email address:", err);
        });
    

    Additionally, if you have deep linking configured in your app to handle your confirmation script URL, you can use the emailConfirm() function in the Android SDK to complete the confirmation step within the app.

    // ... logic to parse token and tokenId
    
    yourStitchClient.emailConfirm("<token>", "<tokenId>").addOnCompleteListener(new OnCompleteListener<Boolean>() {
        @Override
        public void onComplete(@NonNull final Task<Boolean> task) {
            if (task.isSuccessful()) {
                Log.d("stitch", "Successfully confirmed email address!");
                /* code to direct user to log in with their newly confirmed account */
            } else {
                Log.e("stitch", "Error confirming email address:", task.getException());
            }
        }
    });
    

    Once the user email has been confirmed, the user can login with the registered email and password, at which time the user is created in MongoDB Stitch.

    Note

    The user is created upon the first login with the registered email and password; the email confirmation step does not create the user in MongoDB Stitch.

    This means that in the Users interface, you will not be able to view or delete a user who has confirmed their email address but not yet logged in for the first time.

  5. To login with a user’s email and password, the StitchClient provides the logInWithProvider() function, which you can provide with an EmailPasswordAuthProvider.

    yourStitchClient.logInWithProvider(new EmailPasswordAuthProvider("<user-email>", "<user-password>")).addOnCompleteListener(new OnCompleteListener<String>() {
        @Override
        public void onComplete(@NonNull final Task<String> task) {
            if (task.isSuccessful()) {
                Log.d("stitch", "Successfully logged in as user " + task.getResult());
            } else {
                Log.e("stitch", "Error logging in with email/password auth:", task.getException());
            }
        }
    });
    

    This step authenticates the MongoDB Stitch client and begins a Stitch session.

  6. To send a user an email to reset their password, use the sendResetPassword() function.

    yourStitchClient.sendResetPassword("<user-email>").addOnCompleteListener(new OnCompleteListener<Boolean>() {
        @Override
        public void onComplete(@NonNull final Task<Boolean> task) {
            if (task.isSuccessful()) {
                Log.d("stitch", "Successfully sent password reset link!");
            } else {
                Log.e("stitch", "Error sending password reset link:", task.getException());
            }
        }
    });
    

    The user will be sent an email with a password reset link. The reset link includes token and tokenId query parameters.

  7. To reset the password after the user clicks on the link, implement a statically-hosted script at the reset link that will parse the token and tokenId and pass to the passwordReset() function in the JavaScript SDK along with the new password.

    yourStitchClient.auth.provider('userpass').passwordReset('<tokenid>', '<token>', '<new-password>')
        .then(() => {
            console.log("Successfully reset password!");
        })
        .catch(err => {
            console.log("Error resetting password:", err);
        });
    

    Additionally, if you’d like to handle the reset step in the app with deep linking, use the resetPassword() function in the Android SDK.

    yourStitchClient.resetPassword("<token>", "<tokenId>", "<new-password>").addOnCompleteListener(new OnCompleteListener<Boolean>() {
        @Override
        public void onComplete(@NonNull final Task<Boolean> task) {
            if (task.isSuccessful()) {
                Log.d("stitch", "Successfully reset password!");
            } else {
                Log.e("stitch", "Error resetting password:", task.getException());
            }
        }
    });
    

To incorporate email/password authentication into an iOS application, use the following code snippets:

Note

These code snippets are not meant to be a comprehensive step-by-step procedure.

  1. Include the core MongoDB Stitch library.

    import StitchCore
    
  2. Include the code to instantiate a StitchClient.

    See Initialize StitchClient for more details on initializing a StitchClient in your application.

  3. To register a user’s email and password, the StitchClient provides the register() method. This only needs to be called when a user is registering for the first time. Existing users can simply login with the login() method on the StitchClient.

    yourStitchClient.register(email: "<user-email>", password: "<user-password>")
        .done {
            print("Successfully sent confirmation email!")
            /* code to direct user to check their email */
        }.catch { error in
            print("Error registering new user: \(error)")
    }
    

    Upon successful registration, the user is sent a confirmation email with the confirmation link. The confirmation link includes token and tokenId query parameters.

    At this point in the registration flow for new users, you should direct users to check their email for a confirmation link.

    Note

    If the password does not meet the Stitch length requirements, the following error is returned:

    StitchError: password must be between 6 and 128 characters

  4. When the user clicks on the link, there are two possible ways to handle the confirmation step.

    At a minimum, you should implement a statically-hosted confirmation script at the confirmation link using the JavaScript SDK. This script must parse the token and tokenId from the query parameters of the URL and pass it to the emailConfirm() function.

    // ... logic to parse token and tokenId
    
    yourStitchClient.auth.provider('userpass').emailConfirm('<tokenid>', '<token>');
        .then(() => {
            console.log("Successfully confirmed email address!");
            /* code to direct user to log in with their newly confirmed account */
        })
        .catch(err => {
            console.log("Error confirming email address:", err);
        });
    

    Additionally, if you have universal links configured in your app to handle your confirmation script URL, you can use the emailConfirm() function in the iOS SDK to complete the confirmation step within the app.

    // ... logic to parse token and tokenId
    
    yourStitchClient.emailConfirm(token: "<token>", tokenId: "<tokenId>")
        .done {
            print("Successfully confirmed email address!")
        }.catch { error in
            print("Error confirming email address: \(error)")
    }
    

    Once the user email has been confirmed, the user can login with the registered email and password, at which time the user is created in MongoDB Stitch.

    Note

    The user is created upon the first login with the registered email and password; the email confirmation step does not create the user in MongoDB Stitch.

    This means that in the Users interface, you will not be able to view or delete a user who has confirmed their email address but not yet logged in for the first time.

  5. To login with a user’s email and password, the StitchClient provides the login() function, which you can provide with an EmailPasswordAuthProvider.

    yourStitchClient.login(withProvider: EmailPasswordAuthProvider(username: email, password: password))
        .done { (userId: String) in
            print("Successfully logged in as user \(userId)")
        }.catch { error in
            print("Error logging in with email/password auth: \(error)")
    }
    

    This step authenticates the MongoDB Stitch client and begins a Stitch session.

  6. To send a user an email to reset their password, use the sendResetPassword() function.

    yourStitchClient.sendResetPassword(toEmail: "user-email")
        .done {
            print("Successfully sent password reset link!")
        }.catch { error in
            print("Error sending password reset link: \(error)")
    }
    

    The user will be sent an email with a password reset link. The reset link includes token and tokenId query parameters.

  7. To reset the password after the user clicks on the link, implement a statically-hosted script at the reset link that will parse the token and tokenId and pass to the passwordReset() function in the JavaScript SDK along with the new password.

    yourStitchClient.auth.provider('userpass').passwordReset('<tokenid>', '<token>', '<new-password>')
        .then(() => {
            console.log("Successfully reset password!");
        })
        .catch(err => {
            console.log("Error resetting password:", err);
        });
    

    Additionally, if you’d like to handle the reset step in the app with universal links, use the resetPassword() function in the iOS SDK.

    yourStitchClient.resetPassword(token: "<token>", tokenId: "<tokenId>", password: "<new-password>")
        .done {
            print("Successfully reset password!")
        }.catch { error in
            print("Error sending password reset email: \(error)")
    }