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.
Iniciar sesión
Anonymous
La El proveedoranónimo permite a los usuarios iniciar sesión en su aplicación con cuentas efímeras que no tienen información asociada.
Para iniciar sesión, cree una credencial anónima y pásela a 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();
Correo electrónico/Contraseña
El proveedor de autenticación de correo electrónico/contraseña permite a los usuarios iniciar sesión en su aplicación con una dirección de correo electrónico y una contraseña.
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");
Llave API
El proveedor de autenticación de clave API permite que los procesos del servidor accedan a su aplicación directamente o en nombre de un usuario.
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
Función personalizada
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.
Para iniciar sesión con el proveedor de función personalizada, cree una credencial de función personalizada con un objeto payload y páselo a 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" });
JWT personalizado
El proveedor de autenticación Custom JWT le permite gestionar la autenticación de usuarios con cualquier sistema de autenticación que devuelva un JSON web token.
Para iniciar sesión, crea una credencial JWT personalizada con un JWT del sistema externo y pásala a 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");
Autenticación de Facebook
El proveedor de autenticación de Facebook te permite autenticar a los usuarios a través de una app de Facebook usando su cuenta de Facebook. Puedes usar el flujo de autenticación integrado o autenticarte con el SDK de Facebook.
Importante
Habilitar el proveedor de autenticación de Facebook
Para iniciar sesión un usuario con su cuenta de Facebook existente, debe configurar y habilitar el proveedor de autenticación de Facebook para su aplicación.
Importante
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}`); Se abre una nueva ventana con la pantalla de autenticación de Facebook, donde el usuario autentica y autoriza la aplicación. Una vez completado el proceso, la nueva ventana redirige a la URL especificada en la credencial.
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
Puedes utilizar el SDK oficial de Facebook Para gestionar la autenticación del usuario y el flujo de redirección. Una vez autenticado, el SDK de Facebook devuelve un token de acceso que puedes usar para finalizar el inicio de sesión del usuario en tu aplicación.
// 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
El proveedor de autenticación Google le permite autenticar usuarios mediante un proyecto de Google utilizando su cuenta de Google existente.
Nota
Enable the Google Auth Provider
Para autenticar un usuario de Google, debe configurar el proveedor de autenticación de Google.
Iniciar sesión como usuario de Google en tu aplicación es un proceso de dos pasos:
Primero, autentica al usuario con Google. Puedes usar una biblioteca como Google One Tap para una experiencia optimizada.
En segundo lugar, el usuario inicia sesión en su aplicación con un token de autenticación devuelto por Google tras la autenticación exitosa.
Autenticarse con Google One Tap
Nota
Requires OpenID Connect
Google One Tap solo admite la autenticación de usuarios mediante OpenID Connect. Para que los usuarios de Google inicien sesión en tu aplicación web, debes habilitar OpenID Connect en la configuración del proveedor de autenticación de App Services.
Google One Tap es un SDK de Google que permite a los usuarios registrarse o iniciar sesión en un sitio web con un solo clic (o toque).
Ejemplo
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({ idToken: response.credential }); app .logIn(credentials) .then((user) => alert(`Logged in with id: ${user.id}`)); } </script> </html>
Utiliza el flujo OAuth 2.0 de funcionalidad incorporada de Google
Nota
Do Not Use OpenID Connect for Built-In Google OAuth 2.0 Flow
- OpenID Connect no funciona con App Services
- Flujo de Google OAuth 2.0 integrado. Si desea usar OpenID Connect con el SDK web de Realm, utilice el flujo de autenticación con Google One Tap.
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:
Llama a
app.logIn()con una credencial de Google. La credencial debe especificar una URL para tu aplicación que también figure como URI de redireccionamiento en la configuración del proveedor.Se abre una nueva ventana con la pantalla de autenticación de Google, donde el usuario autentica y autoriza la aplicación. Una vez completado el proceso, la nueva ventana redirige a la URL especificada en la credencial.
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.
Ejemplo
Basic Web Login Flow
Este ejemplo muestra cómo configurar la autenticación de Google con App Services en una aplicación web muy básica. La aplicación contiene los siguientes archivos:
. ├── 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>
Importante
Limitaciones de redirección de OAuth 2.0 incorporada para 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.
Para evitar estas limitaciones, aconsejamos utilizar un SDK oficial de Google para obtener un token de acceso de usuario como se describe anteriormente.
Autenticación de Apple
El proveedor de autenticación Apple permite autenticar a los usuarios mediante Sign-in con Apple. Se puede usar el flujo de autenticación incorporado o autenticarse con el SDK de Apple.
Nota
Habilita el proveedor de autenticación de Apple
Para autenticar a un usuario de Apple, debe configurar el proveedor de autenticación Apple.
Utiliza la funcionalidad incorporada de Apple OAuth 2.0
El SDK web de Realm incluye métodos para gestionar el proceso OAuth 2.0 y no requiere la instalación del SDK de Apple JS. El flujo integrado sigue tres pasos principales:
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.
Se llama a
Realm.handleAuthRedirect()en la página redirigida, que almacena el token de acceso de App Services del usuario y cierra la ventana. Tu ventana original de la aplicación detectará automáticamente el acceso token y completará el inicio de sesión del usuario.// 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
Puedes usar el SDK oficial de Iniciar sesión con Apple JS para gestionar la autenticación del usuario y el flujo de redirección. Una vez autenticado, el SDK de Apple JS devuelve un token de ID que puedes usar para finalizar el inicio de sesión del usuario en tu 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.
Obtener un token de acceso de usuario
Cuando un usuario inicia sesión, Atlas App Services crea un token de acceso que le otorga acceso a su aplicación. El SDK de Realm administra automáticamente los tokens de acceso, los actualiza cuando caducan e incluye un token de acceso válido para el usuario actual con cada solicitud. Realm no actualiza automáticamente el token de actualización. Cuando este caduque, el usuario deberá volver a iniciar sesión.
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.
Puedes acceder y actualizar el token de acceso de un usuario con la sesión iniciada en el SDK directamente desde su objeto Realm.User, como se muestra en el siguiente ejemplo:
// 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; }
Expiración del token de actualización
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
Para desconectar a cualquier usuario, llama al User.logOut() en su instancia de usuario.
Log out current user:
await app.currentUser.logOut();
Cerrar sesión del usuario por ID de usuario:
const userId = app.currentUser.id; await app.allUsers[userId].logOut();