Navigation

Authenticate a User

Overview

The Node SDK provides developers with a unified API to authenticate application users for any authentication provider. Users log in by providing authentication credentials for a given authentication provider and the SDK automatically manages authentication tokens and refreshes data for logged in users.

MongoDB Realm provides developers with an API to log application users in and out with any enabled authentication provider. Pass in a credentials object to specify the authentication provider info to the login methods.

The SDK provides the following methods for user authentication:

Method Usage
App.logIn() Call App.logIn() to log a user in with a Realm.Credentials object for an enabled authentication provider. For example, running the script: “app.logIn(Realm.Credentials.emailPassword(‘<email>’, ‘<password>’))” would log in a user created with an email/password authentication provider.
User.logOut() Call User.logOut() to log a user out, regardless of the authentication provider the user was registered using.

Log In

Anonymous

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

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

async function loginAnonymous() {
  // Create an anonymous credential
  const credentials = Realm.Credentials.anonymous();
  try {
    // Authenticate the user
    const user: Realm.User = await app.logIn(credentials);
    // `App.currentUser` updates to match the logged in user
    assert(user.id === app.currentUser.id)
    return user
  } catch(err) {
    console.error("Failed to log in", err);
  }
}
loginAnonymous().then(user => {
  console.log("Successfully logged in!", user)
})
async function loginAnonymous() {
  // Create an anonymous credential
  const credentials = Realm.Credentials.anonymous();
  try {
    // Authenticate the user
    const user = await app.logIn(credentials);
    // `App.currentUser` updates to match the logged in user
    assert(user.id === app.currentUser.id)
    return user
  } catch(err) {
    console.error("Failed to log in", err);
  }
}
loginAnonymous().then(user => {
  console.log("Successfully logged in!", user)
})

Email/Password

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

async function loginEmailPassword(email: string, password: string) {
  // Create an anonymous credential
  const credentials = Realm.Credentials.emailPassword(email, password);
  try {
    // Authenticate the user
    const user: Realm.User = await app.logIn(credentials);
    // `App.currentUser ` updates to match the logged in user
    assert(user.id === app.currentUser.id)
    return user
  } catch(err) {
    console.error("Failed to log in", err);
  }
}
loginEmailPassword("cal.kestis@example.com", "Bogano123!").then(user => {
  console.log("Successfully logged in!", user)
})
async function loginEmailPassword(email, password) {
  // Create an anonymous credential
  const credentials = Realm.Credentials.emailPassword(email, password);
  try {
    // Authenticate the user
    const user = await app.logIn(credentials);
    // `App.currentUser` updates to match the logged in user
    assert(user.id === app.currentUser.id)
    return user
  } catch(err) {
    console.error("Failed to log in", err);
  }
}
loginEmailPassword("cal.kestis@example.com", "Bogano123!").then(user => {
  console.log("Successfully logged in!", user)
})

API Key

The API key authentication provider allows server processes to access 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():

async function loginApiKey(apiKey: string) {
  // Create an API Key credential
  const credentials = Realm.Credentials.apiKey(apiKey);
  try {
    // Authenticate the user
    const user: Realm.User = await app.logIn(credentials);
    // `App.currentUser` updates to match the logged in user
    assert(user.id === app.currentUser.id)
    return user
  } catch(err) {
    console.error("Failed to log in", err);
  }
}
loginApiKey("To0SQOPC...ZOU0xUYvWw").then(user => {
  console.log("Successfully logged in!", user)
})
async function loginApiKey(apiKey) {
  // Create an API Key credential
  const credentials = Realm.Credentials.apiKey(apiKey);
  try {
    // Authenticate the user
    const user = await app.logIn(credentials);
    // `App.currentUser` updates to match the logged in user
    assert(user.id === app.currentUser.id)
    return user
  } catch(err) {
    console.error("Failed to log in", err);
  }
}
loginApiKey("To0SQOPC...ZOU0xUYvWw").then(user => {
  console.log("Successfully logged in!", user)
})

Custom Function

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

async function loginCustomFunction(payload: Realm.Credentials.FunctionPayload) {
  // Create a Custom Function credential
  const credentials = Realm.Credentials.function(payload);
  try {
    // Authenticate the user
    const user: Realm.User = await app.logIn(credentials);
    // `App.currentUser` updates to match the logged in user
    assert(user.id === app.currentUser.id);
    return user;
  } catch (err) {
    console.error("Failed to log in", err);
  }
}
loginCustomFunction({ username: "mongolover" }).then((user) => {
  console.log("Successfully logged in!", user);
});
async function loginCustomFunction(payload) {
  // Create a Custom Function credential
  const credentials = Realm.Credentials.function(payload);
  try {
    // Authenticate the user
    const user = await app.logIn(credentials);
    // `App.currentUser` updates to match the logged in user
    assert(user.id === app.currentUser.id);
    return user;
  } catch (err) {
    console.error("Failed to log in", err);
  }
}
loginCustomFunction({ username: "mongolover" }).then((user) => {
  console.log("Successfully logged in!", user);
});

Custom JWT

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

async function loginCustomJwt(jwt: Realm.Credentials.JWTPayload) {
  // Create a Custom JWT credential
  const credentials = Realm.Credentials.jwt(jwt);
  try {
    // Authenticate the user
    const user: Realm.User = await app.logIn(credentials);
    // `App.currentUser` updates to match the logged in user
    assert(user.id === app.currentUser.id);
    return user;
  } catch (err) {
    console.error("Failed to log in", err);
  }
}
loginCustomJwt("eyJ0eXAi...Q3NJmnU8oP3YkZ8").then((user) => {
  console.log("Successfully logged in!", user);
});
async function loginCustomJwt(jwt) {
  // Create a Custom JWT credential
  const credentials = Realm.Credentials.jwt(jwt);
  try {
    // Authenticate the user
    const user = await app.logIn(credentials);
    // `App.currentUser` updates to match the logged in user
    assert(user.id === app.currentUser.id);
    return user;
  } catch (err) {
    console.error("Failed to log in", err);
  }
}
loginCustomJwt("eyJ0eXAi...Q3NJmnU8oP3YkZ8").then((user) => {
  console.log("Successfully logged in!", user);
});

Facebook OAuth

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

Enable the Facebook Auth Provider

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

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 Node.js app and use to finish logging the user in to your app.

// Get the access token from a client application using the Facebook SDK
const accessToken: string = getFacebookAccessToken();

// Log the user in to your app
const credentials = Realm.Credentials.facebook(accessToken);
app.logIn(credentials).then((user: Realm.User) => {
  console.log(`Logged in with id: ${user.id}`);
});
// Get the access token from a client application using the Facebook SDK
const accessToken = getFacebookAccessToken();

// Log the user in to your app
const credentials = Realm.Credentials.facebook(accessToken);
app.logIn(credentials).then(user => {
  console.log(`Logged in with id: ${user.id}`);
});

Google OAuth

The Google authentication provider allows you to authenticate users through a Google project using their existing Google account.

Enable the Google Auth Provider

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

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

// Get the access token from a client application using the Google SDK
const accessToken: string = getGoogleAccessToken();

// Log the user in to your app
const credentials = Realm.Credentials.google(accessToken);
app.logIn(credentials).then((user: Realm.User) => {
  console.log(`Logged in with id: ${user.id}`);
});
// Get the access token from a client application using the Google SDK
const accessToken = getGoogleAccessToken();

// Log the user in to your app
const credentials = Realm.Credentials.google(accessToken);
app.logIn(credentials).then(user => {
  console.log(`Logged in with id: ${user.id}`);
});

Sign-in with Apple

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

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 Node.js app and use to finish logging the user in to your app.

// Get the access token from a client application using the Apple JS SDK
const idToken: string = getAppleIdToken();

// Log the user in to your app
const credentials = Realm.Credentials.google(idToken);
app.logIn(credentials).then((user: Realm.User) => {
  console.log(`Logged in with id: ${user.id}`);
});
// Get the access token from a client application using the Apple JS SDK
const idToken = getAppleIdToken();

// Log the user in to your app
const credentials = Realm.Credentials.apple(idToken);
app.logIn(credentials).then(user => {
  console.log(`Logged in with id: ${user.id}`);
});

Log Out

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.

// Log out the current user
await app.currentUser.logOut();
// Log out a specific user
await app.allUsers[2].logOut();
// Log out the current user
await app.currentUser.logOut();
// Log out a specific user
await app.allUsers[2].logOut();