Navigation

Email/Password Authentication

Overview

The Email/Password authentication provider allows users to register accounts and log in using their email address and a password. Stitch automatically sends confirmation emails to new accounts when they register. Users must confirm their email address before their account is activated.

Configuration

You can enable and configure the Email/Password authentication provider from the Stitch UI by selecting Email/Password from the Users > Providers page.

You can enable and configure the Email/Password authentication provider with stitch-cli by importing an application directory that contains a configuration file for the provider.

The configuration file must be named local-userpass.json and stored in the /auth_providers directory. Configuration files for the Email/Password authentication provider have the following form:

/auth_providers/local-userpass.json
{
  "name": "local-userpass",
  "type": "local-userpass",
  "config": {
    "emailConfirmationUrl": <string>,
    "emailConfirmationSubject": <string>,
    "resetPasswordSubject": <string>,
    "resetPasswordUrl": <string>
  },
  "disabled": false
}

The Email/Password authentication provider has the following configuration options:

Field Description

Email Confirmation URL

config.emailConfirmationUrl

Required. The base URL of the page that hosts your email confirmation script. The URL must include a scheme, such as http or https.

Note

If you’re developing a mobile application you can handle email confirmation directly in the app by configuring deep linking in Android, or universal links in iOS.

Email Confirmation Subject

config.emailConfirmationSubject

Optional. The subject line of the confirmation email sent to users to when they register a new account. If this is not specified, Stitch will use a default subject instead.

The subject may have a maximum of 256 characters.

Password Reset URL

config.resetPasswordUrl
Required. The base URL of the page that hosts your password reset script. The URL must include a scheme, such as http or https.

Reset Password Email Subject

config.resetPasswordSubject

Optional. The subject line of the email sent to users to when they request to reset their password. If this is not specified, Stitch will use a default subject instead.

The subject may have a maximum of 256 characters.

Usage

Authenticate a User

To log an existing user in to your application, create a UserPasswordCredential instance with the user’s email address and password, and provide that credential instance to the StitchAuth.loginWithCredential() method.

const credential = new UserPasswordCredential("<email>", "<password>")

Stitch.defaultAppClient
  .loginWithCredential(credential).then(authedId => {
     console.log(`successfully logged in with id: ${authedId}`)
  })
    .catch(err => console.error(`login failed with error: ${err}`)

To log an existing user in to your application, instantiate UserPasswordCredential with the user’s email address and password, and provide that credential instance to the StitchAuth.loginWithCredential() method.

UserPasswordCredential credential = new UserPasswordCredential("<email>", "<password>")
Stitch.getDefaultAppClient().getAuth().loginWithCredential(credential)
  .addOnCompleteListener(new OnCompleteListener<StitchUser>() {
    @Override
    public void onComplete(@NonNull final Task<StitchUser> task) {
      if (task.isSuccessful()) {
        Log.d("stitch", "Successfully logged in as user " + task.getResult().getId());
      } else {
        Log.e("stitch", "Error logging in with email/password auth:", task.getException());
      }
    }
  }
);

To log an existing user into your application, instantiate UserPasswordCredential with the user’s email address and password, and provide that credential instance to the StitchAuth.loginWithCredential() method:

let credential = UserPasswordCredential.init()
Stitch.defaultAppClient!.auth.login(withCredential: credential) { result in
  switch result {
  case .success:
      print("Successfully logged in")
  case .failure(let error):
      print("Error logging in with email/password auth: \(error)")
  }
}

Create a New User Account

To register a new user account, obtain a UserPasswordAuthProviderClient instance, and pass the user’s email address and password to the registerWithEmail() method.

Stitch will send the user an email containing a confirmation link. The link points to the Email Confirmation URL specified in the provider configuration and includes unique token and tokenId query parameters.

const emailPassClient = Stitch.defaultAppClient.auth
  .getProviderClient(UserPasswordAuthProviderClient.factory);

emailPassClient.registerWithEmail("<user-email>", "<user-password>")
  .then(() => {
     console.log("Successfully sent account confirmation email!");
  })
  .catch(err => {
     console.log("Error registering new user:", err);
  });

Note

Stitch does not create a user object for a particular user until they have confirmed their email address and successfully logged in. If you need to send a user a new confirmation email, pass their email address to the resendConfirmationEmail() method.

The Email Confirmation URL should point to a page that contains an email confirmation script. The script must parse the token and tokenId values from the URL and pass them to the confirmUser() method.

Stitch.initializeDefaultAppClient("<your app id>");
// Parse the URL query parameters
const url = window.location.search;
const params = new URLSearchParams(url);
const token = params.get('token');
const tokenId = params.get('tokenId');

// Confirm the user's email/password account
const emailPassClient = Stitch.defaultAppClient.auth
  .getProviderClient(UserPasswordAuthProviderClient.factory);

return emailPassClient.confirmUser(token, tokenId);

To reset a user’s password, obtain a UserPasswordAuthProviderClient instance, and pass the user’s email address and password to the registerWithEmail() method. Stitch will send the user an email that contains a confirmation link. The link points to the Email Confirmation URL specified in the provider configuration and includes unique token and tokenId query parameters.

UserPasswordAuthProviderClient emailPassClient = Stitch.getDefaultAppClient().getAuth().getProviderClient(
   UserPasswordAuthProviderClient.factory
);

emailPassClient.registerWithEmail("<user-email>", "<user-password>")
  .addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull final Task<Void> task) {
      if (task.isSuccessful()) {
        Log.d("stitch", "Successfully sent account confirmation email");
      } else {
        Log.e("stitch", "Error registering new user:", task.getException());
      }
    }
  }
);

Note

Stitch does not create a user object for a particular user until they have confirmed their email address and successfully logged in. If you need to send a user a new confirmation email, pass their email address to the resendConfirmationEmail() method.

The Email Confirmation URL should point to a page that contains an email confirmation script. By default the link will open in the user’s web browser. See the JavaScript tab of this section for an example of confirming user emails in the browser.

Alternatively, you can use an Android deep link to open the URL directly in an activity in your app. The activity should parse the query parameters from the deep link intent and pass them to the confirmUser() function along with the token and tokenId values.

public void handlePasswordReset() {
  Uri uri = intent.getIntent().getData();

  String token = uri.getQueryParameter("token");
  String tokenId = uri.getQueryParameter("tokenId");

  UserPasswordAuthProviderClient emailPassClient = Stitch.getDefaultAppClient().getAuth().getProviderClient(
     UserPasswordAuthProviderClient.factory
  );

  emailPassClient.confirmUser(token, tokenId)
    .addOnCompleteListener(new OnCompleteListener<Void>() {
      @Override
      public void onComplete(@NonNull final Task<Void> task) {
        if (task.isSuccessful()) {
          Log.d("stitch", "Successfully reset user's password");
        } else {
          Log.e("stitch", "Error resetting user's password:", task.getException());
        }
      }
    }
}

To create a user, obtain a UserPasswordAuthProviderClient instance, and pass the user’s email address and password to the register() method.

Stitch will send the user an email that contains a confirmation link. The link points to the Email Confirmation URL specified in the provider configuration and includes unique token and tokenId query parameters.

let emailPassClient = Stitch.defaultAppClient!.auth.providerClient(
  fromFactory: userPasswordClientFactory
)

emailPassClient.register(email: "<user-email>", password: "<user-password>") { result in
  switch result {
  case .success:
      print("Registration email sent")
  case .failure(let error):
      print("Error sending registration email")
  }
}

Note

Stitch does not create a user object for a particular user until they have confirmed their email address and successfully logged in. If you need to send a user a new confirmation email, pass their email address to the resendConfirmation() function as the toEmail argument.

The Email Confirmation URL should point to a page that contains an email confirmation script. By default the link will open in the user’s web browser. See the JavaScript tab of this section for an example of confirming user emails in the browser.

Alternatively, you can use an iOS universal link to open the URL directly in your app and handle the confirmation process natively. The application delegate should parse the token and tokenId query parameters from the NSUserActivity object and pass them to the confirmUser() method.

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
    if userActivity.activityType == NSUserActivityTypeBrowsingWeb {
        let url = userActivity.webpageURL!
        let urlString = url.absoluteString

        let queryParams = URLComponents(string: url).queryItems?
        let token = queryParams.first(where: { $0.name == "token" })?.value
        let tokenId = queryParams.first(where: { $0.name == "tokenId" })?.value

        let emailPassClient = Stitch.defaultAppClient!.auth.providerClient(
          fromFactory: userPasswordClientFactory
        )

        emailPassClient.confirmUser(token: token, tokenId: tokenId) { result in
          switch result {
          case .success:
              print("User confirmed")
          case .failure(let error):
              print("Error confirming user: \(error)")
          }
        }
    }
    return true
}

Reset a User’s Password

To reset a user’s password, obtain a UserPasswordAuthProviderClient instance, and call the sendResetPasswordEmail() method with their email address. Stitch will send the user an email containing a password reset link. The link points to the Password Reset URL specified in the provider configuration and includes unique token and tokenId query parameters.

const emailPassClient = Stitch.defaultAppClient.auth
  .getProviderClient(UserPasswordAuthProviderClient.factory);

emailPassClient.sendResetPasswordEmail('<email>').then(() => {
  console.log("Successfully sent password reset email!");
}).catch(err => {
  console.log("Error sending password reset email:", err);
});

The Password Reset URL should point to a page that allows users to, at minimum, input a new a password for their account. When a user submits their new password, pass it to the resetPassword() method along with the token and tokenId values.

// Parse the URL query parameters
const url = window.location.search;
const params = new URLSearchParams(url);

const token = params.get('token');
const tokenId = params.get('tokenId');
const newPassword = getUserInputFromPage();

// Confirm the user's email/password account
const emailPassClient = Stitch.defaultAppClient.auth
  .getProviderClient(UserPasswordAuthProviderClient.factory);

emailPassClient.resetPassword(token, tokenId, newPassword).then(() => {
  console.log("Successfully reset password!");
}).catch(err => {
  console.log("Error resetting password:", err);
});

To reset a user’s password, obtain a UserPasswordAuthProviderClient instance, and call the sendResetPasswordEmail() method with their email address. Stitch will send the user an email that contains a password reset link. The link points to the Password Reset URL specified in the provider configuration and includes unique token and tokenId query parameters.

UserPasswordAuthProviderClient emailPassClient = Stitch.getDefaultAppClient().getAuth().getProviderClient(
   UserPasswordAuthProviderClient.factory
);

emailPassClient.sendResetPasswordEmail("<email>")
  .addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull final Task<Void> task) {
      if (task.isSuccessful()) {
        Log.d("stitch", "Successfully sent password reset email");
      } else {
        Log.e("stitch", "Error sending password reset email:", task.getException());
      }
    }
  }
);

The Password Reset URL should point to a page that, at minimum, allows users to input a new a password for their account. By default the link will open in the user’s web browser. See the JavaScript tab of this section for an example of handling password reset emails in the browser.

Alternatively, you can use an Android deep link to open the URL directly in an activity in your app that handles password resets. When a user submits their new password, pass it to the resetPassword() function along with the token and tokenId values.

public void handlePasswordReset() {
  Uri uri = intent.getIntent().getData();
  EditText newPasswordInput = (EditText) findViewById(R.id.newPasswordInput);

  String token = uri.getQueryParameter("token");
  String tokenId = uri.getQueryParameter("tokenId");
  String newPassword = newPasswordInput.getText().toString();

  UserPasswordAuthProviderClient emailPassClient = Stitch.getDefaultAppClient().getAuth().getProviderClient(
     UserPasswordAuthProviderClient.factory
  );

  emailPassClient
      .resetPassword(token, tokenId, newPassword)
      .addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull final Task<Void> task) {
          if (task.isSuccessful()) {
            Log.d("stitch", "Successfully reset user's password");
          } else {
            Log.e("stitch", "Error resetting user's password:", task.getException());
          }
        }
      }
}

To reset a user’s password, obtain a UserPasswordAuthProviderClient instance, and call the sendResetPasswordEmail() method with their email address. Stitch will send the user an email that contains a password reset link. The link points to the Password Reset URL specified in the provider configuration and includes unique token and tokenId query parameters.

let emailPassClient = Stitch.defaultAppClient!.auth.providerClient(
  fromFactory: userPasswordClientFactory
)

emailPassClient.sendResetPassword(toEmail: "<email>")
    .done { (userId: String) in
        print("Successfully sent password reset email")
    }.catch { error in
        print("Error logging in with email/password auth: \(error)")
    }

The Password Reset URL should point to a page that, at minimum, allows users to input a new a password for their account. By default the link will open in the user’s web browser. See the JavaScript tab of this section for an example of handling password reset emails in the browser.

Alternatively, you can use an iOS universal link to open the URL directly in your app and handle the password reset process natively. When a user submits their new password, pass it to the reset() function along with the token and tokenId values.

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
    if userActivity.activityType == NSUserActivityTypeBrowsingWeb {
        let url = userActivity.webpageURL!
        let urlString = url.absoluteString

        let queryParams = URLComponents(string: url).queryItems?
        let token = queryParams.first(where: { $0.name == "token" })?.value
        let tokenId = queryParams.first(where: { $0.name == "tokenId" })?.value

        // Instantiate and load the password reset view controller here
    }
    return true
}

func handlePasswordReset(newPassword: String) {
  let emailPassClient = Stitch.defaultAppClient!.auth.providerClient(
    fromFactory: userPasswordClientFactory
  )

  emailPassClient.reset(token: token, tokenId: tokenId, password: newPassword) { result in
    switch result {
    case .success:
        print("User password reset")
    case .failure(let error):
        print("Error resetting password: \(error)")
    }
  }
}