Navigation

Authenticate a User

Overview

MongoDB Realm provides an API for authenticating users using any enabled authentication provider. Instantiate a Credentials object and pass it to either of the app.login() or app.loginAsync() methods to authenticate a user login and create a User object. Each authentication provider corresponds to a static helper method used to instantiate Credentials objects using that authentication providers. See the table below to find the method that instantiates the Credentials instance for your authentication provider:

Authentication Provider Credentials Generation Method
Anonymous Credentials.anonymous()
Email/Password Credentials.emailPassword(String email, String password)
API Key Credentials.apiKey(String key)
Custom Function Credentials.customFunction(String functionName, Object... arguments)
Custom JWT Credentials.jwt(String jwtToken)
Google OAuth Credentials.google(String googleToken)
Facebook OAuth Credentials.facebook(String accessToken)
Sign-in With Apple Credentials.apple(String idToken)

Log In

You can authenticate users with either the app.login() or app.loginAsync() methods of your application’s instance of the io.realm.mongodb.App class. While the app.login() method blocks code execution in the calling thread until the supplied credentials have either succeeded or failed to authenticate a user, the app.loginAsync() method allows execution to continue, handling success or failure with a callback function that is guaranteed to execute on the same thread that called app.loginAsync().

If successful, the app.login() method returns a User object. In the event of a failure, the app.login() method throws an exception of type ObjectServerError.

Pass a callback to the app.loginAsync() method to handle success or failure. This callback accepts a single parameter of type App.Result. The isSuccess() method of the App.Result object passed to the callback returns a boolean that indicates whether the operation succeeded. In the event of a failure, you can view the error that caused the failure using the getError() method.

Anonymous

The anonymous authentication provider enables users to log in to your application with short-term accounts that store no persistent personal information. To log in with anonymous authentication, create an anonymous credential by calling Credentials.anonymous() and then pass the generated credential to app.login() or app.loginAsync().

Realm.init(this) // context, usually an Activity or Application
val appID = "<your app ID>" // replace this with your App ID
val app: App = App(AppConfiguration.Builder(appID)
       .build())

val anonymousCredentials: Credentials = Credentials.anonymous()

val user: User? = null
app.loginAsync(anonymousCredentials) {
   if (it.isSuccess) {
       Log.v(TAG, "Successfully authenticated anonymously.")
       user = app.currentUser()
   } else {
       Log.e(TAG, it.error.toString())
   }
}
Realm.init(this); // context, usually an Activity or Application
String appID = "<your app ID>"; // replace this with your App ID
App app = new App(new AppConfiguration.Builder(appID)
      .build());

Credentials anonymousCredentials = Credentials.anonymous();

app.loginAsync(anonymousCredentials, it -> {
      if (it.isSuccess()) {
         Log.v(TAG, "Successfully authenticated anonymously.");
         user = app.currentUser();
      } else {
         Log.e(TAG, it.getError().toString());
      }
});

Email/Password

The Email/Password authentication provider enables users to log in to your application with an email username and a password. To log in with email/password authentication, create an email/password credential by calling Credentials.emailPassword() with the user’s email and password. Then pass the generated credential to app.login() or app.loginAsync().

Realm.init(this) // context, usually an Activity or Application
val appID = "<your app ID>" // replace this with your App ID
val app: App = App(AppConfiguration.Builder(appID)
       .build())

val emailPasswordCredentials: Credentials = Credentials.emailPassword("<email>", "<password>")

val user: User? = null
app.loginAsync(emailPasswordCredentials) {
   if (it.isSuccess) {
       Log.v(TAG, "Successfully authenticated using an email and password.")
       user = app.currentUser()
   } else {
       Log.e(TAG, it.error.toString())
   }
}
Realm.init(this); // context, usually an Activity or Application
String appID = "<your app ID>"; // replace this with your App ID
App app = new App(new AppConfiguration.Builder(appID)
      .build());

Credentials emailPasswordCredentials = Credentials.emailPassword("<email>", "<password>");

app.loginAsync(emailPasswordCredentials, it -> {
      if (it.isSuccess()) {
         Log.v(TAG, "Successfully authenticated using an email and password.");
         user = app.currentUser();
      } else {
         Log.e(TAG, it.getError().toString());
      }
});

API Key

The API Key authentication provider enables users to log in to your application with an API Key generated automatically in the client SDK. To log in with API Key authentication, create an API Key credential by calling Credentials.apiKey() with an API Key. Then pass the generated credential to app.login() or app.loginAsync().

Realm.init(this) // context, usually an Activity or Application
val appID = "<your app ID>" // replace this with your App ID
val app: App = App(AppConfiguration.Builder(appID)
      .build())

val apiKeyCredentials: Credentials = Credentials.apiKey("<key>")

app.loginAsync(apiKeyCredentials) {
   if (it.isSuccess) {
         Log.v(TAG, "Successfully authenticated using an API Key.")
         val user: User? = app.currentUser()
   } else {
         Log.e(TAG, "Error logging in: ${it.error.toString()}")
   }
}
Realm.init(this); // context, usually an Activity or Application
String appID = "<your app ID>"; // replace this with your App ID
App app = new App(new AppConfiguration.Builder(appID)
      .build());

Credentials apiKeyCredentials = Credentials.apiKey("<key>");

app.loginAsync(apiKeyCredentials, it -> {
      if (it.isSuccess()) {
         Log.v(TAG, "Successfully authenticated using an API Key.");
         user = app.currentUser();
      } else {
         Log.e(TAG, it.getError().toString());
      }
});

Custom Function

The Custom Function authentication provider enables users to log in to your application using a Realm Function defined in your Realm app. To log in with custom function authentication, create a credential by calling Credentials.customFunction(). The customFunction() method expects a Document that contains the properties and values used by the Realm auth function. For example, suppose the backend function expects the input parameter to include a field named username, like this:

exports = async function(loginPayload) {
   const { username } = loginPayload;
   ...
}

The document you pass to Credentials.customFunction() might look like this:

Document("username", "bob")

You then pass the generated credential to app.login() or app.loginAsync().

Realm.init(this) // context, usually an Activity or Application
val appID = "<your app ID>" // replace this with your App ID
val app: App = App(AppConfiguration.Builder(appID).build())

val customFunctionCredentials:
   Credentials = Credentials.customFunction(Document("username","bob"))

app.loginAsync(customFunctionCredentials) {
   if (it.isSuccess) {
      Log.v(TAG, "Successfully authenticated using a custom function.")
      val user: User? = app.currentUser()
   } else {
      Log.e(TAG, "Error logging in: ${it.error.toString()}")
   }
}
Realm.init(this); // context, usually an Activity or Application
String appID = "<your app ID>"; // replace this with your App ID
App app = new App(new AppConfiguration.Builder(appID).build());

Credentials customFunctionCredentials =
   Credentials.customFunction(new Document("username", "bob"));

app.loginAsync(customFunctionCredentials, it -> {
   if (it.isSuccess()) {
      Log.v(TAG, "Successfully authenticated using a custom function.");
      user = app.currentUser();
   } else {
      Log.e(TAG, it.getError().toString());
   }
});

Custom JWT

The Custom JWT authentication provider enables users to log in to your application with a custom JSON Web Token. To log in with custom JWT authentication, create a custom JWT credential by calling Credentials.jwt() with your custom JWT. Then pass the generated credential to app.login() or app.loginAsync().

Realm.init(this) // context, usually an Activity or Application
val appID = "<your app ID>" // replace this with your App ID
val app: App = App(AppConfiguration.Builder(appID).build())

// fetch JWT from custom provider
val customJWTCredentials: Credentials = Credentials.jwt("<token>")

app.loginAsync(customJWTCredentials) {
   if (it.isSuccess) {
         Log.v(TAG, "Successfully authenticated using a custom JWT.")
         val user: User? = app.currentUser()
   } else {
         Log.e(TAG, "Error logging in: ${it.error.toString()}")
   }
}
Realm.init(this); // context, usually an Activity or Application
String appID = "<your app ID>"; // replace this with your App ID
App app = new App(new AppConfiguration.Builder(appID)
      .build());

// fetch JWT from custom provider
Credentials customJWTCredentials = Credentials.jwt("<token>");

app.loginAsync(customJWTCredentials, it -> {
      if (it.isSuccess()) {
         Log.v(TAG, "Successfully authenticated using a custom JWT.");
         user = app.currentUser();
      } else {
         Log.e(TAG, it.getError().toString());
      }
});

Facebook OAuth

The Facebook OAuth authentication provider enables users to log in to your application with a custom token provided by Facebook. To log in with Facebook OAuth authentication, create a Facebook OAuth credential by calling Credentials.facebook() with the token provided by Facebook. Then pass the generated credential to app.login() or app.loginAsync().

Realm.init(this) // context, usually an Activity or Application
val appID = "<your app ID>" // replace this with your App ID
val app: App = App(AppConfiguration.Builder(appID)
       .build())

// fetch facebook token using Facebook SDK

val facebookCredentials: Credentials = Credentials.facebook("<token>")

app.loginAsync(facebookCredentials) {
   if (it.isSuccess) {
         Log.v(TAG, "Successfully authenticated using Facebook OAuth.")
         val user: User? = app.currentUser()
   } else {
         Log.e(TAG, "Error logging in: ${it.error.toString()}")
   }
}
Realm.init(this); // context, usually an Activity or Application
String appID = "<your app ID>"; // replace this with your App ID
App app = new App(new AppConfiguration.Builder(appID)
      .build());

// fetch facebook token using Facebook SDK

Credentials facebookCredentials = Credentials.facebook("<token>");

app.loginAsync(facebookCredentials, it -> {
      if (it.isSuccess()) {
         Log.v(TAG, "Successfully authenticated using Facebook OAuth.");
         user = app.currentUser();
      } else {
         Log.e(TAG, it.getError().toString());
      }
});

Google OAuth

The Google OAuth authentication provider enables users to log in to your application with a custom token provided by Google. To log in with Google OAuth authentication, create a Google OAuth credential by calling Credentials.google() with the token provided by Google. Then pass the generated credential to app.login() or app.loginAsync().

Realm.init(this) // context, usually an Activity or Application
val appID = "<your app ID>" // replace this with your App ID
val app: App = App(AppConfiguration.Builder(appID)
       .build())

// fetch google token using Google SDK

val googleCredentials: Credentials = Credentials.google("<token>")

app.loginAsync(googleCredentials) {
   if (it.isSuccess) {
         Log.v(TAG, "Successfully authenticated using Google OAuth.")
         val user: User? = app.currentUser()
   } else {
         Log.e(TAG, "Error logging in: ${it.error.toString()}")
   }
}
Realm.init(this); // context, usually an Activity or Application
String appID = "<your app ID>"; // replace this with your App ID
App app = new App(new AppConfiguration.Builder(appID)
      .build());

// fetch google token using Google SDK

Credentials googleCredentials = Credentials.google("<token>");

app.loginAsync(googleCredentials, it -> {
      if (it.isSuccess()) {
         Log.v(TAG, "Successfully authenticated using Google OAuth.");
         user = app.currentUser();
      } else {
         Log.e(TAG, it.getError().toString());
      }
});

Sign-in with Apple

The Sign-in with Apple authentication provider enables users to log in to your application with a custom token provided by Apple. To log in with Sign-in with Apple authentication, create a Sign-in with Apple credential by calling Credentials.apple() with the token provided by Apple. Then pass the generated credential to app.login() or app.loginAsync().

Realm.init(this) // context, usually an Activity or Application
val appID = "<your app ID>" // replace this with your App ID
val app: App = App(AppConfiguration.Builder(appID)
       .build())

// fetch apple token using Apple SDK

val appleCredentials: Credentials = Credentials.apple("<token>")

app.loginAsync(appleCredentials) {
   if (it.isSuccess) {
         Log.v(TAG, "Successfully authenticated using Sign-in with Apple.")
         val user: User? = app.currentUser()
   } else {
         Log.e(TAG, "Error logging in: ${it.error.toString()}")
   }
}
Realm.init(this); // context, usually an Activity or Application
String appID = "<your app ID>"; // replace this with your App ID
App app = new App(new AppConfiguration.Builder(appID)
      .build());

// fetch apple token using Apple SDK

Credentials appleCredentials = Credentials.apple("<token>");

app.loginAsync(customJWTCredentials, it -> {
      if (it.isSuccess()) {
         Log.v(TAG, "Successfully authenticated using Sign-in with Apple.");
         user = app.currentUser();
      } else {
         Log.e(TAG, it.getError().toString());
      }
});

Log Out

You can log out any user, regardless of the authentication provider used to log in, using the user.logOut() or user.logOutAsync() methods. Both methods:

  • delete locally stored user credentials from the device
  • immediately halt any synchronization to and from the user’s realms
  • mark the user’s realms for deletion the next time the app restarts

Because logging out halts synchronization, you should only log out after all local Realm updates have uploaded to the server.

Warning

When a user logs out, you can no longer read or write data in any synced realms that the user opened. As a result, any operation that has not yet completed before the initiating user logs out cannot complete successfully and will likely result in an error. Any data in a write operation that fails in this way will be lost.

user?.logOutAsync {
   if (it.isSuccess) {
         Log.v(TAG, "Successfully logged out.")
   } else {
         Log.e(TAG, it.error.toString())
   }
}
user.logOutAsync( it -> {
   if (it.isSuccess()) {
      Log.v(TAG, "Successfully logged out.");
   } else {
      Log.e(TAG, it.getError().toString());
   }
});