Docs Menu

Authenticate Users - Java SDK

On this page

  • Log In
  • Anonymous User
  • Email/Password User
  • API Key User
  • Custom JWT User
  • Custom Function User
  • Facebook User
  • Google User
  • Apple User
  • Offline Login
  • Log a User Out

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

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

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

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

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

The Custom Function authentication provider enables users to log in to your application using a Realm Function defined in your 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().

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

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

Important

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

To set up your application for Google User authentication:

  1. In the Google Cloud Platform console, create an OAuth 2.0 client ID of type "Web application".
  2. Configure your backend App to use that client ID and the associated client secret.
  3. Enable OpenID Connect on the backend.

Use Google's official Sign-In for Android to authenticate Google users in your Android application:

Note
Code Example Below

For an implementation of these instructions, check out the code block below.

  1. Add the Google Sign-In for Android dependency to the dependencies block of your application level build.gradle:

    com.google.android.gms:play-services-auth:19.2.0
  2. Create a GoogleSignInOptions with the following builder options:

  3. Use the GoogleSignInOptions to create a GoogleSignInClient with GoogleSignIn.getClient()
  4. Use the GoogleSignInClient to create an Intent capable of triggering Google Sign-In.
  5. Use registerForActivityResult() to configure a callback. Your callback should use GoogleSignIn.getSignedInAccountFromIntent() to access the result of Google Sign-In: a Task<GoogleSignInAccount>.
  6. Use the launch() method of the ActivityResultLauncher returned in the previous step to start Google Sign-In. Pass the launch() method your Google Sign-In Intent.
  7. Use isSuccessful() to handle Google Sign-In errors.
  8. Access the result of the task (a GoogleSignInAccount) with getResult().
  9. Access the ID token for the GoogleSignInAccount with getIdToken().
  10. Create a Realm Credentials object with Credentials.google(). Pass the ID token as the first parameter, and GoogleAuthType.ID_TOKEN as the second parameter.
  11. Use the app.loginAsync() or app.login() methods to authenticate with the App Services backend using the token.

The following code implements this flow, starting with a method call to loginWithGoogle():

Tip
See also:

To learn more about Google Sign-In for Android, check out the official Google Sign-In for Android Integration Guide.

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

Tip

If you get a Login failed error saying that the token contains an invalid number of segments, verify that you're passing a UTF-8-encoded string version of the JWT.

Atlas App Services manages sessions with access tokens and refresh tokens. Client SDKs supply the logic to manage tokens, and provide them with requests.

The SDK stores these tokens in Shared Preferences.

Tip
See also:

When your Realm application authenticates a user, it caches the user's credentials. You can check for existing user credentials to bypass the login flow and access the cached user. Use this to open a realm offline.

Note
Initial login requires a network connection

When a user signs up for your app, or logs in for the first time with an existing account on a client, the client must have a network connection. Checking for cached user credentials lets you open a realm offline, but only if the user has previously logged in while online.

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

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

←  Connect to an Atlas App Services backend - Java SDKSync Changes Between Devices - Java SDK →
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.