Navigation

Authenticate a User

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.

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)
})

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)
})

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

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)
})

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);
});

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);
});

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.

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.

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

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}`);
});

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

Info With Circle IconCreated with Sketch.Note
Enable the Google Auth Provider

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

Logging a Google user in to your Realm app is a two step process:

  1. First, you authenticate the user with Google. You can use a library like Google One Tap for a streamlined experience.
  2. Second, you log the user in to your Realm app with an authentication token returned by Google upon successful user authentication.
Info With Circle IconCreated with Sketch.Note
Requires OpenID Connect

Google One Tap only supports user authentication through OpenID Connect. To log Google users in to your web app, you must enable OpenID Connect in the authentication provider configuration.

import * as Realm from "realm-web";
import googleOneTap from 'google-one-tap';
const app = new Realm.App("<Your Realm App ID>");
const client_id = "<Your Google Client ID>";
// Open the Google One Tap menu
googleOneTap({ client_id }, async (response: { credential: string }) => {
// Upon successful Google authentication, log in to Realm with the user's credential
const credentials = Realm.Credentials.google(response.credential)
const user = await app.logIn(credentials);
console.log(`Logged in with id: ${user.id}`);
});

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

  1. You call app.logIn() with a Google 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 Google 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.google(redirectUri);
// Calling logIn() opens a Google 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();
Important With Circle IconCreated with Sketch.Important
Built-In OAuth 2.0 Redirect Limitations for Google

Due to changes in OAuth application verification requirements, the built-in OAuth 2.0 process faces limitations when authenticating Google users. If you use the Google login redirect flow using Realm's redirect flow, a maximum of 100 Google users may authenticate while the app is in development/testing/staging and all users will see an unverified application notification before they authenticate.

To avoid these limitations, we advise that you use an official Google SDK to get a user access token as described above.

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.

Info With Circle IconCreated with Sketch.Note
Enable the Apple Auth Provider

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

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

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}`);
});

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();
Give Feedback