Navigation

Authenticate a User

Overview

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

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("joe.jasper@example.com", "passw0rd").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("joe.jasper@example.com", "passw0rd").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. You can use the built-in authentication flow or authenticate with the Facebook SDK.

Enable the Facebook Auth Provider

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

Built-In OAuth 2.0 Flow

The Realm Web SDK includes methods to handle the OAuth 2.0 process and does not require you to install the Facebook SDK. The built in flow follows three main steps:

  1. You call app.logIn() with a Facebook credential. The credential must specify a URL for your app that is also listed as a redirect URI in the provider configuration.
  2. A new window opens to a Facebook authentication screen and the user authenticates and authorizes your app in that window. Once complete, the new window redirects to the URL specified in the credential.
  3. You call handleAuthRedirect() on the redirected page, which stores the user’s Realm access token and closes the window. Your original app window will automatically detect the access token and finish logging the user in.
// The redirect URI should be on the same domain as this app and
// specified in the auth provider configuration.
const redirectUri = "https://app.example.com/handleOAuthLogin";
const credentials = Realm.Credentials.facebook(redirectUri);

// Calling logIn() opens a Facebook authentication screen in a new window.
app.logIn(credentials).then((user: Realm.User) => {
  // The logIn() promise will not resolve until you call `handleAuthRedirect()`
  // from the new window after the user has successfully authenticated.
  console.log(`Logged in with id: ${user.id}`);
})

// When the user is redirected back to your app, handle the redirect to
// save the user's access token and close the redirect window. This
// returns focus to the original application window and automatically
// logs the user in.
Realm.handleAuthRedirect();
// The redirect URI should be on the same domain as this app and
// specified in the auth provider configuration.
const redirectUri = "https://app.example.com/handleOAuthLogin";
const credentials = Realm.Credentials.facebook(redirectUri);

// Calling logIn() opens a Facebook authentication screen in a new window.
app.logIn(credentials).then(user => {
  // The logIn() promise will not resolve until you call `handleAuthRedirect()`
  // from the new window after the user has successfully authenticated.
  console.log(`Logged in with id: ${user.id}`);
})

// When the user is redirected back to your app, handle the redirect to
// save the user's access token and close the redirect window. This
// returns focus to the original application window and automatically
// logs the user in.
Realm.handleAuthRedirect();

Authenticate with the Facebook SDK

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

// Get the access token from the Facebook SDK
const { accessToken } = FB.getAuthResponse();
// Define credentials with the access token from the Facebook SDK
const credentials = Realm.Credentials.facebook(accessToken);
// Log the user in to your app
app.logIn(credentials).then((user: Realm.User) => {
  console.log(`Logged in with id: ${user.id}`);
});
// Get the access token from the Facebook SDK
const { accessToken } = FB.getAuthResponse();
// Define credentials with the access token from the Facebook SDK
const credentials = Realm.Credentials.facebook(accessToken);
// Log the user in to your app
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. Once authenticated, the Google SDK returns an authorization code that you can use to finish logging the user in to your app.

// Get the access token from the Google SDK
function getGoogleAuthCode(): Promise<string> {
  return new Promise(() => {
    gapi.auth2.authorize({
      client_id: "<Google Client ID>",
      // Scopes should match the metadata fields in the provider configuration
      scope: "<scopes>",
      response_type: "code",
    }, ({ code, error }) => {
      if(error) {
        reject(error)
      }
      resolve(code)
    })
  })
}
getGoogleAuthCode()
  .then((code: string) => {
    // Define credentials with the authorization code from the Google SDK
    const credentials = Realm.Credentials.google(code)
    // Log the user in to your app
    return app.logIn(credentials)
  })
  .then((user: Realm.User) => {
    console.log(`Logged in with id: ${user.id}`);
  });
// Get the access token from the Google SDK
function getGoogleAuthCode() {
  return new Promise(() => {
    gapi.auth2.authorize({
      client_id: "<Google Client ID>",
      // Scopes should match the metadata fields in the provider configuration
      scope: "<scopes>",
      response_type: "code",
    }, ({ code, error }) => {
      if(error) {
        reject(error)
      }
      resolve(code)
    })
  })
}
getGoogleAuthCode()
  .then(code => {
    // Define credentials with the authorization code from the Google SDK
    const credentials = Realm.Credentials.google(code)
    // Log the user in to your app
    return app.logIn(credentials)
  })
  .then(user => {
    console.log(`Logged in with id: ${user.id}`);
  });

(Deprecated) Built-In OAuth 2.0 Flow

The Realm Web SDK no longer includes built-in methods to handle the OAuth 2.0 process. Instead, use the official Google SDK as described above.

Apple OAuth

The Apple authentication provider allows you to authenticate users through Sign-in With Apple. You can use the built-in authentication flow or authenticate with the Apple SDK.

Enable the Apple Auth Provider

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

Built-In OAuth 2.0 Flow

The Realm Web SDK includes methods to handle the OAuth 2.0 process and does not require you to install the Apple JS SDK. The built in flow follows three main steps:

  1. You call app.logIn() with an Apple credential. The credential must specify a URL for your app that is also listed as a redirect URI in the provider configuration.
  2. A new window opens to an Apple authentication screen and the user authenticates and authorizes your app in that window. Once complete, the new window redirects to the URL specified in the credential.
  3. You call handleAuthRedirect() on the redirected page, which stores the user’s Realm access token and closes the window. Your original app window will automatically detect the access token and finish logging the user in.
// The redirect URI must be on the same domain as this app and
// must be specified in the auth provider configuration.
const redirectUri = "https://app.example.com/handleOAuthLogin";
const credentials = Realm.Credentials.apple(redirectUri);

// Calling logIn() opens an Apple authentication screen in a new window.
app.logIn(credentials).then((user: Realm.User) => {
  // The logIn() promise will not resolve until you call `handleAuthRedirect()`
  // from the new window after the user has successfully authenticated.
  console.log(`Logged in with id: ${user.id}`);
})

// When the user is redirected back to your app, handle the redirect to
// save the user's access token and close the redirect window. This
// returns focus to the original application window and automatically
// logs the user in.
Realm.handleAuthRedirect();
// The redirect URI should be on the same domain as this app and
// specified in the auth provider configuration.
const redirectUri = "https://app.example.com/handleOAuthLogin";
const credentials = Realm.Credentials.apple(redirectUri);

// Calling logIn() opens an Apple authentication screen in a new window.
app.logIn(credentials).then(user => {
  // The logIn() promise will not resolve until you call `handleAuthRedirect()`
  // from the new window after the user has successfully authenticated.
  console.log(`Logged in with id: ${user.id}`);
})

// When the user is redirected back to your app, handle the redirect to
// save the user's access token and close the redirect window. This
// returns focus to the original application window and automatically
// logs the user in.
Realm.handleAuthRedirect();

Authenticate with the Apple SDK

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

// Get the ID token from the Apple SDK
AppleID.auth.signIn()
  .then(({ id_token: string }) => {
    // Define credentials with the ID token from the Apple SDK
    const credentials = Realm.Credentials.apple(id_token)
    // Log the user in to your app
    return app.logIn(credentials)
  })
  .then((user: Realm.User) => {
    console.log(`Logged in with id: ${user.id}`);
  });
// Get the ID token from the Apple SDK
AppleID.auth.signIn()
  .then(({ id_token }) => {
    // Define credentials with the ID token from the Apple SDK
    const credentials = Realm.Credentials.apple(id_token)
    // Log the user in to your app
    return 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.

// 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();