Authenticate a User - Web SDK
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(); // 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; } const user = await loginAnonymous();
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 email/password credential const credentials = Realm.Credentials.emailPassword(email, password); // 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; } const user = await loginEmailPassword("joe.jasper@example.com", "passw0rd");
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.apiKey(apiKey); // 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; } const user = await loginApiKey(REALM_API_KEY.key); // add previously generated API key
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); // 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; } const user = await loginCustomFunction({ username: "ilovemongodb" });
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); // 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; } const user = await loginCustomJwt("eyJ0eXAi...Q3NJmnU8oP3YkZ8");
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.
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.
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.// 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. const user = await app.logIn(credentials); // The app.logIn() promise will not resolve until you call `Realm.handleAuthRedirect()` // from the new window after the user has successfully authenticated. console.log(`Logged in with id: ${user.id}`); 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
Realm.handleAuthRedirect()
on the redirected page, which stores the user's Atlas App Services access token and closes the window. Your original app window will automatically detect the access token and finish logging the user in.// 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 await app.logIn(credentials);
Google Authentication
The Google authentication provider allows you to authenticate users through a Google project using their existing Google account.
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 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 App with an authentication token returned by Google upon successful user authentication.
Authenticate with Google One Tap
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 App Services 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).
Example
Basic Google One Tap Flow
This example shows how to set up Google Authentication with App Services in
a very basic web app. The app only contains an index.html
file.
<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 App Services. --> <div id="g_id_onload" data-client_id="<your_google_client_id>" data-callback="handleCredentialsResponse" ></div> </body> <!-- Load Atlas App Services --> <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 App Services function handleCredentialsResponse(response) { const credentials = Realm.Credentials.google({ id_token: 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
Note
Do Not Use OpenID Connect for Built-In Google OAuth 2.0 Flow
- OpenID Connect does not work with App Services'
- 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
Realm.handleAuthRedirect()
on the redirected page, which stores the user's App Services access token and closes the window. Your original app window will automatically detect the access token and finish logging the user in.
Example
Basic Web Login Flow
This example shows how to set up Google Authentication with App Services in a very basic web app. The app has the following files:
. ├── auth.html └── index.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 Realm --> <script src="https://unpkg.com/realm-web/dist/bundle.iife.js"></script> <!-- Log in with App Services and Google Authentication --> <script> const app = new Realm.App({ id: "<Your-App-ID>", }); const authButton = document.getElementById("google-auth"); authButton.addEventListener("click", () => { // The redirect URL should be on the same domain as this app and // specified in the auth provider configuration. const redirectUrl = "http://yourDomain/auth.html"; const credentials = Realm.Credentials.google({ redirectUrl }); // 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>
<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>
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 App Services' 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.
Note
Enable the Apple Auth Provider
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.// 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. const user = app.logIn(credentials); // The logIn() promise will not resolve until you call `Realm.handleAuthRedirect()` // from the new window after the user has successfully authenticated. console.log(`Logged in with id: ${user.id}`); 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
Realm.handleAuthRedirect()
on the redirected page, which stores the user's App Services access token and closes the window. Your original app window will automatically detect the access token and finish logging the user in.// 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 const { id_token } = await AppleID.auth.signIn(); // Define credentials with the ID token from the Apple SDK const credentials = Realm.Credentials.apple(id_token); // Log the user in to your app const user = await app.logIn(credentials);
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.
Get a User Access Token
When a user logs in, Atlas App Services creates an access token for the user that grants them access to your App. The Realm SDK automatically manages access tokens, refreshes them when they expire, and includes a valid access token for the current user with each request. Realm does not automatically refresh the refresh token. When the refresh token expires, the user must log in again.
If you send requests outside of the SDK, you need to include the user's access token with each request and manually refresh the token when it expires.
You can access and refresh a logged in user's access token in the SDK from their
Realm.User
object, as in the following example:
// Gets a valid user access token to authenticate requests async function getValidAccessToken(user) { // An already logged in user's access token might be stale. To // guarantee that the token is valid, refresh it if necessary. await user.refreshAccessToken(); return user.accessToken; }
Refresh Token Expiration
Refresh tokens expire after a set period of time. When the refresh token expires, the access token can no longer be refreshed and the user must log in again.
For information on configuring refresh token expiration, refer to Manage User Sessions in the App Services documentation.
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();