Authenticate a User
On this page
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 = await app.logIn(credentials); // `App.currentUser` updates to match the logged in user console.assert(user.id === app.currentUser.id); return user; } catch (err) { console.error("Failed to log in", err); } } const user = await loginAnonymous(); console.log("Successfully logged in!", user.id);
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, 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 console.assert(user.id === app.currentUser.id); return user; } catch (err) { console.error("Failed to log in", err); } } const user = await loginEmailPassword("joe.jasper@example.com", "passw0rd"); console.log("Successfully logged in!", user);
API Key
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) { // Create an API Key credential const credentials = Realm.Credentials.serverApiKey(apiKey); try { // Authenticate the user const user = await app.logIn(credentials); // `App.currentUser` updates to match the logged in user console.assert(user.id === app.currentUser.id); return user; } catch (err) { console.error("Failed to log in", err); } } const user = await loginApiKey(REALM_API_KEY.key); // add previously generated API key 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) { // 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 console.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) { // 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 console.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 Authentication
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.
To log a user in with their existing Facebook account, you must configure and enable the Facebook authentication provider for your application.
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.
Use the Built-In Facebook 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:
- 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. - 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.
- 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) => { // 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) => { console.log(`Logged in with id: ${user.id}`); });
Google Authentication
The Google authentication provider allows you to authenticate users through a Google project using their existing Google account.
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:
- First, you authenticate the user with Google. You can use a library like Google One Tap for a streamlined experience.
- Second, you log the user in to your Realm app with an authentication token returned by Google upon successful user authentication.
Authenticate with Google One Tap
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 Realm authentication provider configuration.
Google One Tap is a Google SDK that lets users sign up to or log in to a website with one click (or tap).
This example shows how to set up Google Authentication with Realm in
a very basic web app. The app only contains an index.html
file.
<!DOCTYPE html> <html lang="en"> <head> <title>Google One Tap Example</title> </head> <body> <h1>Google One Tap Example</h1> <!-- The data-callback HTML attribute sets the callback function that is run when the user logs in. Here we're calling the handleCredentialsResponse JavaScript function defined in the below script section to log the user into Realm. --> <div id="g_id_onload" data-client_id="<your_google_client_id>" data-callback="handleCredentialsResponse" ></div> </body> <!-- Load MongoDB Realm --> <script src="https://unpkg.com/realm-web/dist/bundle.iife.js"></script> <!-- Load Google One Tap --> <script src="https://accounts.google.com/gsi/client"></script> <!-- Log in with Realm and Google Authentication --> <script async defer> const app = new Realm.App({ id: "<your_realm_app_id>", }); // Callback used in `data-callback` to handle Google's response and log user into Realm function handleCredentialsResponse(response) { const credentials = Realm.Credentials.google(response.credential); app .logIn(credentials) .then((user) => alert(`Logged in with id: ${user.id}`)); } </script> </html>
Use the Built-In Google OAuth 2.0 Flow
- OpenID Connect does not work with Realm's
- built-in Google OAuth 2.0 flow. If you'd like to use OpenID Connect with the Realm Web SDK, use the Authentication with Google One Tap flow.
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:
- 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. - 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.
- 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.
This example shows how to set up Google Authentication with Realm in a very basic web app. The app has the following files:
. ├── auth.html ├── index.html
<!DOCTYPE html> <html lang="en"> <head> <title>Google Auth Example</title> </head> <body> <h1>Google Auth Example</h1> <button id="google-auth">Authenticate!</button> </body> <!-- Load MongoDB Realm --> <script src="https://unpkg.com/realm-web/dist/bundle.iife.js"></script> <!-- Log in with Realm and Google Authentication --> <script> const app = new Realm.App({ id: "<Your-App-ID>", }); const authButton = document.getElementById("google-auth"); authButton.addEventListener("click", () => { // The redirect URI should be on the same domain as this app and // specified in the auth provider configuration. const redirectUri = "http://yourDomain/auth.html"; const credentials = Realm.Credentials.google(redirectUri); // Calling logIn() opens a Google 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}`); }) .catch((err) => console.error(err)); }); </script> </html>
<!DOCTYPE html> <html lang="en"> <head> <title>Google Auth Redirect</title> </head> <body> <p>Redirects come here for Google Authentication</p> </body> <script> Realm.handleAuthRedirect(); </script> </html>
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.
Apple Authentication
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.
To authenticate an Apple user, you must configure the Apple authentication provider.
Use the Built-In Apple 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:
- 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. - 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.
- 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.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 }) => { // 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}`); });
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.
Log Out
To log any user out, call the User.logOut()
on their user instance.
Log out current user:
await app.currentUser.logOut();
Log out user by user ID:
const userId = app.currentUser.id; await app.allUsers[userId].logOut();