Docs Menu

Authenticate Users - React Native SDK

On this page

  • Log In
  • User Sessions
  • 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

MongoDB Realm provides an API for authenticating users using any enabled authentication provider. Instantiate a Credentials object and pass it to the app.login() method to authenticate a user login and create a User object.

MongoDB Realm manages sessions with access tokens and refresh tokens. Client SDKs supply the logic to manage tokens, and provide them with requests.

For web browsers, the JavaScript SDK stores these tokens in HTML5 local storage.

Tip
See also:

The Anonymous provider allows users to log in to your application with temporary accounts that have no associated information.

To log in, create an anonymous credential and pass it to App.logIn():

The email/password authentication provider allows users to log in to your application with an email address and a password.

To log in, create an email/password credential with the user's email address and password and pass it to App.logIn():

The API key authentication provider allows server processes to access your app directly or on behalf of a user.

To log in with an API key, create an API Key credential with a server or user API key and pass it to App.logIn():

The Custom JWT authentication provider allows you to handle user authentication with any authentication system that returns a JSON web token.

To log in, create a Custom JWT credential with a JWT from the external system and pass it to App.logIn():

The Custom Function authentication provider allows you to handle user authentication by running a function that receives a payload of arbitrary information about a user.

To log in with the custom function provider, create a Custom Function credential with a payload object and pass it to App.logIn():

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.

You can use the official Facebook SDK to handle the user authentication and redirect flow from a client application. Once authenticated, the Facebook SDK returns an access token that you can send to your React Native app and use to finish logging the user in to your app.

The Google authentication provider allows you to authenticate users with their existing Google account.

Note
Enable the Google Auth Provider

To authenticate a Google user, you must configure the Google authentication provider.

There is no official Sign in with Google integration with React Native. The simplest approach to integrating Sign in With Google into your React Native app with Realm authentication is to use a third-party library. The below example uses the library React Native Google Sign In. You can also build your own solution using Google Identity Services to handle the user authentication and redirect flow from a client application.

Regardless of implementation, you must retrieve an ID token from the Google Authorization server. Use that ID token to log into Realm.

// Get the Google OAuth 2.0 access token
const idToken = getGoogleAccessToken();
// Log the user in to your app
const credentials = Realm.Credentials.google({ idToken });
app.logIn(credentials).then((user) => {
console.log(`Logged in with id: ${user.id}`);
});
Example
Authenticate with Google in React Native

This example uses the library React Native Google Sign In. In addition to the React Native code, you must also set up additional configuration in your project's ios and android directories to use Sign in with Google. Refer to the package's documentation for iOS-specific and Android-specific documentation.

SignInWithGoogleButton.jsx
import { useState } from "react";
import {
GoogleSignin,
GoogleSigninButton,
statusCodes,
} from "@react-native-google-signin/google-signin";
import Realm from "realm";
// Instantiate Realm app
const realm = new Realm.App({
id: "<Your App ID>",
});
// Configure Google Auth
GoogleSignin.configure({
webClientId: "<Your Web Client ID>",
});
export default function GoogleSignInButton() {
const [signinInProgress, setSigninInProgress] = useState(false);
const signIn = async () => {
setSigninInProgress(true);
try {
// Sign into Google
await GoogleSignin.hasPlayServices();
const { idToken } = await GoogleSignin.signIn();
// use Google ID token to sign into Realm
const credential = Realm.Credentials.google({ idToken });
const user = await realm.logIn(credential);
console.log("signed in as Realm user", user.id);
} catch (error) {
// handle errors
if (error.code === statusCodes.SIGN_IN_CANCELLED) {
// user cancelled the login flow
} else if (error.code === statusCodes.IN_PROGRESS) {
// operation (e.g. sign in) is in progress already
} else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
// play services not available or outdated
} else {
// some other error happened
}
} finally {
setSigninInProgress(false);
}
};
// return Google Sign in button component
return (
<GoogleSigninButton
style={{ width: 192, height: 48 }}
size={GoogleSigninButton.Size.Wide}
color={GoogleSigninButton.Color.Dark}
onPress={signIn}
disabled={signinInProgress}
/>
);
}

The Apple authentication provider allows you to authenticate users through Sign-in With Apple.

Note
Enable the Apple Auth Provider

To authenticate an Apple user, you must configure the Apple authentication provider.

You can use the official Sign in with Apple JS SDK to handle the user authentication and redirect flow from a client application. Once authenticated, the Apple JS SDK returns an ID token that you can send to your React Native app and use to finish logging the user in to your app.

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.

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.

// Log the user into the backend app.
// The first time you login, the user must have a network connection.
const getUser = async () => {
// Check for an existing user.
// If the user is offline but credentials are
// cached, this returns the existing user.
if (app.currentUser) return app.currentUser;
// If the device has no cached user credentials, log them in.
const credentials = Realm.Credentials.anonymous();
return await app.logIn(credentials);
};

To learn how to use the cached user in the Sync Configuration and access a realm while offline, read the Open a Synced Realm While Offline docs.

To log any user out, call the User.logOut() on their user instance.

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.

←  Create and Delete Users - React Native SDKSync Changes Between Devices - React Native SDK →
Give Feedback
© 2022 MongoDB, Inc.

About

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