Email/Password Authentication
On this page
Overview
Email/password authentication lets users register and login using an email address. Atlas App Services must confirm Email/Password users before they may log in.
The following diagram shows the process flow for logging in:
Note
User email addresses are case-sensitive. For example, a user with the
email address TestAccount@example.com
could not log in using the
testaccount@example.com
address.
Configuration
In the left navigation, click Authentication.
In the list of Authentication providers, select Email/Password. From this screen, you can configure and enable the provider. Use the following sections to guide you through the process.
To enable and configure the Email/Password authentication provider with
the App Services CLI, define a configuration
object for it in /auth/providers.json
.
Email/Password provider configurations have the following form:
{ "local-userpass": { "name": "local-userpass", "type": "local-userpass", "config": { "autoConfirm": <boolean>, "emailConfirmationUrl": <string>, "confirmEmailSubject": <string>, "runConfirmationFunction": <boolean>, "confirmationFunctionName": <string>, "resetPasswordUrl": <string>, "resetPasswordSubject": <string>, "runResetFunction": <boolean>, "resetFunctionName": <string>, }, "disabled": <boolean> } }
Tip
The name
of an authentication provider is always the same as its type
.
User Confirmation
Before an email/password user can authenticate, your app must register and confirm the user's new account. Registering an email/password user creates a new user object. App Services then requires confirmation of the account. You can select one of three methods to confirm a new user account:
The following diagram shows the process flow for confirming a user:
New User Account Status
A user account can be in one of 2 states: Pending and Confirmed.
When the confirmation process is started, Atlas App Services creates a user account and sets the status to Pending Confirmation. In this state, the user cannot login. Because the email address is now associated with a user account, any attempt to re-register the same email will fail.
With the account in the pending state, the user must confirm their account before logging in. When the user confirms their account, Atlas App Services sets the status to Confirmed and the user can log in.
If you are automatically confirming users, the account is created with the status set to Confirmed and the user can log on immediately after registering.
Warning
Only use automatic confirmation when you are developing and testing your app. Production applications should always use a secure confirmation process.
You can view a list of pending user accounts in the UI or via the App Services APIs:
In the left navigation, under Data Access, click App Users.
At the top of the list of users, select the Pending filter.
To view pending users with the Realm CLI, use the
appservices users list
command and include the --pending
option.
To view pending users with the Admin API, use the List Users endpoint.
Send a Confirmation Email
With this confirmation method, users must respond to an email upon registration. The email contains a link to a confirmation URL. The user must visit this link within 30 minutes to confirm that they control the email address.
Configure the following settings to have App Services automatically send a confirmation email:
Email Confirmation URL: the base of the URL included in every confirmation email. App Services appends a unique
token
andtokenId
to this URL. These serve as query parameters to create a unique link for every confirmation. To confirm the user, first extract these query parameters from the user's unique URL. Then, pass thetoken
andtokenId
to the Client SDK'sconfirmUser
function.Mobile applications can handle email confirmation directly in the app. To do this, configure deep linking in Android or universal links in iOS.
Email Confirmation Subject: the subject line for the email that App Services sends. This value is optional if omitted, App Services uses a default subject line instead. Custom email confirmation subjects can contain a maximum of 256 characters.
Note
Confirmation emails are not currently customizable beyond the base URL and
subject line. In particular, they always come from a mongodb.com
email
address.
For production apps, you can use a confirmation function rather than the built-in confirmation email method. Confirmation functions allow you to build entirely custom email confirmations. See Run a Confirmation Function for more information.
Run a Confirmation Function
You can Run a Confirmation Function when a new user registers. App Services passes a confirmation token, a token ID, and the user's email to the function that you create. Your function then performs the logic you need to confirm the user, and then returns one of the following result objects, which are explained in more detail below:
{ status: 'success' }
{ status: 'fail' }
{ status: 'pending' }
Within the function, you define custom logic to confirm users. For example, your function might:
Send custom confirmation emails from a specific domain. Send these with a particular template using an external service.
Read user permissions from a collection in MongoDB Atlas or an external REST service.
Send confirmation messages through a service other than email, such as SMS.
The custom confirmation function signature has one parameter. It is an object that contains user data and confirmation tokens. These fields are:
Field | Description |
---|---|
username | The user's email address. |
token | A unique value used to confirm the user's identity. You use this when
calling the SDK's Confirm User function. |
tokenId | A unique value used to confirm the user's identity. You use this when
calling the SDK's Confirm User function. |
The custom user confirmation function returns an object with a status field. The following table describes the potential values of this field:
Status | Effect |
---|---|
success | App Services confirms the user's identity, allowing the user to log
into their new account. |
pending | App Services changes the user's confirmation status to Pending Confirmation .
This does not confirm the user's identity or allow login.
The client application must call the SDK's Confirm User function to
finalize the process. |
fail | App Services does not create a user account. The user can only retry
account confirmation by registering again. Since the previous account
doesn't exist, the user can reuse the same username (email). |
The following is an example of a user confirmation function that:
Checks that the email provided is a valid email.
Confirms that the given email address has access to a particular service.
Sends an SMS message to the user.
If the message is sent successfully, informs Atlas App Services to create a new account with a Pending status.
exports = ({ token, tokenId, username }) => { // Validate the username const isValidEmail = myCustomValidatorService.validate(username); // Check if the user has access to this service const isPrivileged = myCustomAuthorizationService.hasAccess(username) // Send a message to the user so that they can confirm themselves const msgSendSuccessful = isValidEmail && isPrivileged && mySmsService.send(username, token, tokenId) if ( msgSendSuccessful ) { return { status: 'pending' }; } else { return { status: 'fail' }; } }
Unless the custom function automatically confirms the user, you must provide a means for the user to complete the confirmation process after the function fires. After completing any additional confirmation steps, call the SDK's Confirm User method to finalize the user account creation on Atlas App Services.
Automatically Confirm Users
You can configure the provider to Automatically Confirm Users. When selected, App Services immediately confirms new Email/Password users after registration.
Warning
App Services does not validate automatically confirmed email addresses. As a result, there are a few reasons you may not be able to contact such users via email:
An automatically confirmed user's email address might not actually belong to that user. (e.g. a user could sign up as
steve.jobs@apple.com
)A user's email address may not even be a valid email address. (e.g. a user could sign up as
my.name@gmail
orasdavaskljj
)
Exercise caution with this option. Securely resetting the password of a user account with no valid contact information can be very difficult.
Password Resets
An email/password user may forget their password and need to reset it. For security reasons, you should confirm the user's identity before completing the password reset. App Services provides two ways to do this:
After confirming the user's identity, you can complete the password reset request. Once the password reset has been completed, the user can log in using the new password.
Send a Password Reset Email
You can configure the provider to Send a Password Reset Email. When a user requests a password reset, App Services sends a Password Reset URL to a user's email address. The user must visit this URL within 30 minutes.
When you configure password reset emails, you can configure the following settings:
Password Reset URL: the base of the URL included in every password reset email. App Services appends a unique
token
andtokenId
to this URL. These serve as query parameters to create a unique link for every password reset. To reset the user's password, extract these query parameters from the user's unique URL. Pass the token and tokenId to the Client SDK'sresetPassword
function.Reset Password Email Subject: the subject line for the email that App Services sends. This value is optional: if omitted, App Services uses a default subject line instead. Custom password reset subjects can contain a maximum of 256 characters.
Mobile applications can handle password resets directly in the app. Configure deep linking in Android or universal links in iOS.
Note
Password reset emails are not currently customizable beyond the base URL and
subject line. In particular, they always come from a mongodb.com
email
address.
For production apps, you can use a custom password reset function rather than the built-in password reset email method. Custom functions allow you to build entirely custom email confirmations, or use a method other than email to confirm a password reset request.
Run a Password Reset Function
You can configure the provider to Run a Password Reset
Function. You define a Function for App Services to
run when you callResetPasswordFunction()
in the SDK.
App Services passes the user's email, the desired new password, a confirmation
token, and a token ID to the function that you create. Your function then
performs the logic you need to confirm the user's identity prior to resetting
the password.
App Services can immediately reset the user's password. Or you can require additional confirmation from the client application.
The App Services function must return an object containing a status
key.
The key maps to a string with one of the following values, which are explained
in more detail below:
{ status: 'success' }
{ status: 'fail' }
{ status: 'pending' }
Warning
The Realm SDK function callResetPasswordFunction()
is not
authenticated. Its password recovery is intended only for users who
cannot otherwise log into their account. As a result, you cannot associate
any call to this function with a specific App Services user. Returning a
success
status permanently changes the password to the new value in the
password
parameter of the function. So returning success
can result
in any user resetting the password of any other application user. For
security, you should send the account owner a message via
a trusted mode of communication and return pending
.
You can use a custom password reset function to define your own password reset flows:
Send custom password reset emails from a specific domain with a particular template using an external service.
Interface with a MongoDB Atlas collection to implement a password reset "cooldown period". This can prevent too many password reset attempts on a single account in a particular time range.
Send custom password reset messages through a service other than email.
Note
Using a password reset function is mutually exclusive with configuring
App Services to send a password reset email. When you configure password
reset to use a custom function, calling sendResetPasswordEmail()
in the client SDK returns an error.
The custom password reset function signature is variadic: it accepts any number of parameters. The first is always an object containing user data and confirmation tokens. All following parameters are custom parameters. They are passed into the Client SDK as an argument collection. For instance, the Client SDK call:
callResetPasswordFunction("myUsername", "newPassword", ["Security Question Answer 1", "Security Question Answer 2", "securityCode:0510"])
Becomes this customized signature for the password reset function:
resetFunc({username, password, token, tokenId, currentPasswordValid}, securityAnswer1, securityAnswer2, securitySMSCode)
In the custom password reset function, an object must be passed as the first parameter. The following table describes the fields found in this object:
Field | Description |
---|---|
username | The email address of the user. |
password | A new proposed password for the user. If this function returns the
successful status, this is the user's new password. |
token | A unique value used to update the user's password. |
tokenId | A unique value used to confirm the user's identity
using the SDK confirmUser function. |
currentPasswordValid | A boolean that is true if a user requests to change their password
to their existing password. |
The custom password reset function must return an object that contains a
status
field. The value of this status
field may be one of:
Status | Password Reset State | SDK Effect |
---|---|---|
success | App Services changes the user's password to the provided password
parameter immediately. Only return success if you authenticate the user's
identity in the custom function. You might do this with a security question
or other secure means. | If the custom function call returns a success , your client app
can interpret the lack of an error as a successful password reset.
The user can sign in using the new password. |
pending | App Services waits for the client application to take some additional
action to complete the password reset. For example, the custom
password reset function may send a token and tokenId via email
or SMS to verify the user's identity. | The SDK method that calls this function does not take a return value, so
it does not directly handle a pending case. You must implement custom
logic in your application to complete the password reset process. For
example, you might implement a deep link or universal link in the client
to extract the token and tokenId , and then call the
resetPassword method to complete a reset. |
fail | Nothing happens. | The SDK interprets a returned fail as an error or exception
when calling the custom password reset function. |
A custom password reset function may include elements similar to this example:
exports = ({ token, tokenId, username, password, currentPasswordValid }) => { // check if the username corresponds to a real user const isUser = myCustomValidator.validate(username); // check if the user is attempting to reset their password to their current password if (currentPasswordValid) { myCustomNotifier.sendMessage(username, "Cannot reset password to current password."); return { status: 'fail' }; } // check if the user has requested a password reset too often recently const isNotCoolingDown = myCustomCooldownService.canReset(username, 'myCustomService') // send a message to the user in some way so that the user can confirm themselves const msgSendSuccessful = isUser && isNotCoolingDown && myCustomMsgr.send(username, token, tokenId) if ( msgSendSuccessful ) { return { status: 'pending' }; } else { return { status: 'fail' }; } }
Examples
For examples of registration, log in, and password reset flows using email/password authentication, see the Realm SDKs:
Summary
Email/password authentication allows users to create an identity in your application based on a username and a password.
To enable Email/password authentication, your application should support a method of email confirmation, and a method of resetting a user's password. There are multiple implementation options for each of these requirements.