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.

Enable and Configure Email/Password Authentication

To configure for email/password authentication,

  1. Click Authentication. The page displays the Authentication Providers.

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

  3. In the Edit Provider dialog,

    1. Switch the Email/Password to enabled. If enabling email/password authentication for the first time, ignore this step.

    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:

    import { StitchClientFactory } from 'mongodb-stitch';
    
    const stitchClientPromise = StitchClientFactory.create('<your-app-id>');
    

    Replace <your-app-id> with your MongoDB Stitch app ID. In the MongoDB Stitch console, you can find your App ID in the Clients view. StitchClientFactory.create() returns a promise that resolves to a StitchClient after initialization. The client only needs to be resolved once and it can be used for the lifetime of an 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.

    stitchClientPromise.then(stitchClient => {
        stitchClient.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);
            });
    });
    

    If sucessful, the user will be 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.

  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
    
    stitchClientPromise.then(stitchClient => {
        stitchClient.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 User Management 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.

    stitchClientPromise.then(stitchClient => {
        stitchClient.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.

    stitchClientPromise.then(stitchClient => {
        stitchClient.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.

    stitchClientPromise.then(stitchClient => {
        stitchClient.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:

    final StitchClient _client = new StitchClient(this, "<your-app-id>");
    

    Replace <your-app-id> with your MongoDB Stitch app ID. In the MongoDB Stitch console, you can find your App ID in the Clients view.

  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.

    _client.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());
            }
        }
    });
    

    If sucessful, the user will be 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.

  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.

    import { StitchClientFactory } from 'mongodb-stitch';
    
    // ... logic to parse token and tokenId
    
    const stitchClientPromise = StitchClientFactory.create('<your-app-id>');
    stitchClientPromise.then(stitchClient => {
        stitchClient.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
    
    _client.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 User Management 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.

    _client.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.

    _client.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.

    import { StitchClientFactory } from 'mongodb-stitch';
    
    const stitchClientPromise = StitchClientFactory.create('<your-app-id>');
    stitchClientPromise.then(stitchClient => {
        stitchClient.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.

    _client.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:

    let stitchClient = StitchClient(appId: "<your-app-id>")
    

    Replace <your-app-id> with your MongoDB Stitch app ID. In the MongoDB Stitch console, you can find your App ID in the Clients view.

  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.

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

    If sucessful, the user will be 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.

  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.

    import { StitchClientFactory } from 'mongodb-stitch';
    
    // ... logic to parse token and tokenId
    
    const stitchClientPromise = StitchClientFactory.create('<your-app-id>');
    stitchClientPromise.then(stitchClient => {
        stitchClient.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
    
    stitchClient?.emailConfirm(token: "<token>", tokenId: "<tokenId>")
        .then {
            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 User Management 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.

    stitchClient?.login(withProvider: EmailPasswordAuthProvider(username: email, password: password))
        .then { (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.

    stitchClient?.sendResetPassword(toEmail: "user-email")
        .then {
            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.

    stitchClient.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.

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