Navigation

Authenticate a User

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 ProviderCredentials Generation Method
AnonymousCredentials.anonymous()
Email/PasswordCredentials.emailPassword(String email, String password)
API KeyCredentials.apiKey(String key)
Custom FunctionCredentials.customFunction(String functionName, Object... arguments)
Custom JWTCredentials.jwt(String jwtToken)
Google OAuthCredentials.google(String googleToken)
Facebook OAuthCredentials.facebook(String accessToken)
Sign-in With AppleCredentials.apple(String idToken)

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.

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().

val appID = YOUR_APP_ID // replace this with your App ID
val app: App = App(
AppConfiguration.Builder(appID)
.build()
)
val anonymousCredentials: Credentials = Credentials.anonymous()
var user: User?
app.loginAsync(anonymousCredentials) {
if (it.isSuccess) {
Log.v("AUTH", "Successfully authenticated anonymously.")
user = app.currentUser()
} else {
Log.e("AUTH", it.error.toString())
}
}

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().

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>"
)
var user: User? = null
app.loginAsync(emailPasswordCredentials) {
if (it.isSuccess) {
Log.v("AUTH", "Successfully authenticated using an email and password.")
user = app.currentUser()
} else {
Log.e("AUTH", it.error.toString())
}
}

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().

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>")
var user: User? = null
app.loginAsync(apiKeyCredentials) {
if (it.isSuccess) {
Log.v("AUTH", "Successfully authenticated using an API Key.")
user = app.currentUser()
} else {
Log.e("AUTH", "Error logging in: ${it.error.toString()}")
}
}

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().

val appID = YOUR_APP_ID // replace this with your App ID
val app: App = App(
AppConfiguration.Builder(appID)
.build()
)
val customFunctionCredentials:
Credentials = Credentials.customFunction(org.bson.Document("username", "bob"))
var user: User? = null
app.loginAsync(customFunctionCredentials) {
if (it.isSuccess) {
Log.v("AUTH", "Successfully authenticated using a custom function.")
user = app.currentUser()
} else {
Log.e("AUTH", "Error logging in: ${it.error.toString()}")
}
}

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().

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>")
var user: User? = null
app.loginAsync(customJWTCredentials) {
if (it.isSuccess) {
Log.v("AUTH", "Successfully authenticated using a custom JWT.")
user = app.currentUser()
} else {
Log.e("AUTH", "Error logging in: ${it.error.toString()}")
}
}

The Facebook authentication provider allows you to authenticate users through a Facebook app using their existing Facebook account.

Important With Circle IconCreated with Sketch.Important
Enable the Facebook Auth Provider

To log a user in with their existing Facebook account, you must configure and enable the Facebook authentication provider for your application.

Important With Circle IconCreated with Sketch.Important
Do Not Store Facebook Profile Picture URLs

Facebook profile picture URLs include the user's access token to grant permission to the image. To ensure security, do not store a URL that includes a user's access token. Instead, access the URL directly from the user's metadata fields when you need to fetch the image.

Follow the official Facebook Login for Android Quickstart to set up the authentication flow for your application. In the login completion handler, get the logged in user's access token from the Facebook LoginResult. Use the access token to create a Realm Facebook credential and then log the user into your Realm app.

FacebookSdk.setApplicationId("YOUR FACEBOOK SDK APP ID")
FacebookSdk.sdkInitialize(activity)
val callbackManager = CallbackManager.Factory.create()
LoginManager.getInstance().registerCallback(
callbackManager,
object : FacebookCallback<LoginResult> {
override fun onSuccess(loginResult: LoginResult) {
// Signed in successfully, forward credentials to MongoDB Realm.
val accessToken = loginResult.accessToken
val facebookCredentials: Credentials =
Credentials.facebook(accessToken.token)
app.loginAsync(facebookCredentials) {
if (it.isSuccess) {
Log.v(
"AUTH",
"Successfully logged in to MongoDB Realm using Facebook OAuth."
)
} else {
Log.e("AUTH", "Failed to log in to MongoDB Realm", it.error)
}
}
}
override fun onCancel() {
Log.v("AUTH", "Cancelled Facebook login")
}
override fun onError(exception: FacebookException) {
Log.e("AUTH", "Failed to authenticate with Facebook: ${exception.message}")
}
})
Important With Circle IconCreated with Sketch.Important

To log a user in with their existing Google account, you must configure and enable the Google authentication provider for your application.

Follow the official Google Sign-In for Android Integration Guide to set up the authentication flow for your application. In the sign-in completion handler, get the logged in user's authorization code from the GoogleSignInAccount object. Use the authorization code to create a Realm Google credential and then log the user into your Realm app.

fun loginWithGoogle() {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("YOUR GOOGLE SDK APP ID")
.requestEmail()
.build()
val googleSignInClient = GoogleSignIn.getClient(this, gso)
val account = GoogleSignIn.getLastSignedInAccount(this)
val signInIntent: Intent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN) // RC_SIGN_IN lets onActivityResult identify the result of THIS call
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
handleSignInResult(task)
}
}
fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
try {
val account: GoogleSignInAccount? = completedTask.result
val authorizationCode: String? = account?.serverAuthCode
val googleCredentials: Credentials = Credentials.google(authorizationCode)
app.loginAsync(googleCredentials) {
if (it.isSuccess) {
Log.v(
"AUTH",
"Successfully logged in to MongoDB Realm using Google OAuth."
)
} else {
Log.e("AUTH", "Failed to log in to MongoDB Realm", it.error)
}
}
} catch (e: ApiException) {
Log.e("AUTH", "Failed to authenticate using Google OAuth: " + e.message);
}
}

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().

val appID = YOUR_APP_ID // replace this with your App ID
val app: App = App(
AppConfiguration.Builder(appID)
.build()
)
// fetch IDToken using Apple SDK
val appleCredentials: Credentials = Credentials.apple("<token>")
var user: User? = null
app.loginAsync(appleCredentials) {
if (it.isSuccess) {
Log.v("AUTH", "Successfully authenticated using Sign-in with Apple.")
user = app.currentUser()
} else {
Log.e("AUTH", "Error logging in: ${it.error.toString()}")
}
}

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.

user?.logOutAsync {
if (it.isSuccess) {
Log.v("AUTH", "Successfully logged out.")
} else {
Log.e("AUTH", it.error.toString())
}
}
Give Feedback