Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
Administrar usuarios

Authenticate Users - React Native SDK

@realm/react Tiene ganchos para la autenticación de usuarios. useAuth y useEmailPasswordAuth manejan la autenticación con proveedores de autenticación habilitados.

For a quick useAuth reference, refer to useAuth Hook on this page. For a quick useEmailPasswordAuth reference, refer to useEmailPasswordAuth Hook on the Manage Email/Password Users page.

También puedes usar directamente las APIs de Realm.js. Instancia un objeto Credenciales y pásalo a App.logIn() para autenticarte y obtener un objeto Usuario.

Before you can authenticate a user, you must:

@realm/react has providers and hooks for user authentication. To configure user authentication:

  1. Configura los proveedores de @realm/react.

  2. Write a fallback component for UserProvider.

Components wrapped by AppProvider can access the useApp and useAuth hooks. These components only render if AppProvider successfully connects to your App Services backend.

Los componentes encapsulados por UserProvider pueden acceder a usuarios autenticados con el gancho useUser. Estos componentes solo se renderizan si la aplicación tiene un usuario autenticado.

To configure user authentication:

  1. Envuelva todos los componentes que necesitan acceder a App Services en AppProvider.

  2. Dentro de AppProvider, envuelva todos los componentes a los que desea que tenga acceso un usuario autenticado con UserProvider.

  3. En UserProvider, incluya una propiedad fallback con un componente que inicie sesión a un usuario. La aplicación representa este componente si no hay ningún usuario autenticado.

import React from 'react';
import {AppProvider, UserProvider} from '@realm/react';
// Fallback log in component that's defined in another file.
import {LogIn} from './Login';
export const LoginExample = () => {
return (
<ScrollView>
<AppProvider id={APP_ID}>
{/* If there is no authenticated user, mount the
`fallback` component. When user successfully
authenticates, the app unmounts the `fallback`
component (in this case, the `LogIn` component). */}
<UserProvider fallback={LogIn}>
{/* Components inside UserProvider have access
to the user. These components only mount if
there's an authenticated user. */}
<UserInformation />
</UserProvider>
</AppProvider>
</ScrollView>
);
};

If your app doesn't have an authenticated and logged-in user, UserProvider and its children will not render. To handle this case, you can pass a fallback component to UserProvider. This is commonly the login screen for apps.

The following example uses anonymous authentication, but you could use any of the useAuth methods.

To write an authentication fallback component for UserProvider:

  1. Crear un componente funcional.

  2. Destructure logInWithAnonymous and result from the useAuth hook.

  3. Call logInWithAnonymous() within a useEffect block that has an empty dependency array.

  4. Gestione result. Si la operación de autenticación no tiene éxito, puedes guardar el manejo de errores basándote en result.

export const LogIn = () => {
// `logInWithAnonymous` logs in a user using an
// anonymous Realm Credential.
// `result` gives us access to the result of the
// current operation. In this case, `logInWithAnonymous`.
const {logInWithAnonymous, result} = useAuth();
// Log in an anyonmous user on component render.
// On successful login, this fallback component unmounts.
useEffect(() => {
logInWithAnonymous();
}, [])
return (
<View >
{!result.error && <Text>Please log in</Text>}
<View>
{result.pending && <ActivityIndicator />}
{result.error && <ErrorComponent error={result.error} />}
</View>
</View>
);
};

El SDK de React Native se comunica con Atlas App Services para gestionar sesiones con tokens de acceso y tokens de actualización.

Para obtener más información sobre la gestión de sesiones, consulte Sesiones de usuario en la documentación de App Services.

Después de configurar la autenticación de usuario en tu cliente y los proveedores de autenticación en tu aplicación de App Services, puedes iniciar sesión de usuario.

The Anonymous provider allows users to log in to your application with temporary accounts that have no associated information.

Calling an authentication method when a user is currently logged in, switches the current user to the new user.

If you call logInWithAnonymous() in the fallback of the UserProvider, then UserProvider's children render as soon as the anonymous log in succeeds.

To log in an anonymous user:

  1. Destructure logInWithAnonymous and result from the useAuth hook.

  2. Llamar logInWithAnonymous() sin argumentos.

  3. Handle the result.

export const LogInWithAnonymous = () => {
const {logInWithAnonymous, result} = useAuth();
const performAnonymousLogin = logInWithAnonymous;
// Handle `result`...
};

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.

Puedes usar el hook useEmailPasswordAuth para gestionar el inicio de sesión del usuario en tu cliente. Para una referencia rápida de useEmailPasswordAuth, consulta el Hook de usoAuthEmailPassword en la página Gestionar Usuarios por Email/Contraseña.

To log a user in with email and password:

  1. Destructure logIn and result from the useEmailPasswordAuth hook.

  2. Pass the user's email and password to LogIn() as an object.

  3. Handle the result.

export const LoginWithEmail = () => {
const {logIn, result} = useEmailPasswordAuth();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const performLogin = () => {
logIn({email, password});
};
// Handle `result`...
};

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.

Before you can log a user in with an API key, you need to create an API key.

Para iniciar sesión con una clave API:

  1. Destructure loginWithApiKey and result from the useAuth hook.

  2. Pase su clave API a loginWithApiKey().

const loginApiKeyUser = async (apiKey: ApiKey) => {
try {
logInWithApiKey(apiKey!.key);
} catch (error) {
console.log(error);
}
};

The Custom JWT authentication provider handles user authentication with any authentication system that returns a JSON web token.

To log in a custom JWT user:

  1. Set up the JWT authentication provider in your App Services backend.

  2. Get a JWT from an external system.

  3. Destructure logInWithJWT and result from the useAuth hook.

  4. Pasa el JWT a logInWithJWT().

  5. Handle the result.

export const LogInWithJWT = () => {
const {logInWithJWT, result} = useAuth();
// Get the current anonymous user so we can call
// an App Services Function later.
const anonymousUser = useUser();
const performJWTLogin = async () => {
// Get a JWT from a provider. In this case, from
// an App Services Function called "generateJWT".
const token = (await anonymousUser.functions.generateJWT()) as string;
logInWithJWT(token);
};
// Handle `result`...
};

El proveedor de autenticación de funciones personalizadas permite gestionar la autenticación de usuarios mediante la ejecución de una función que recibe una carga útil con información arbitraria sobre el usuario.Consulte Autenticación de funciones personalizadas para obtener más información.

To log in a user with the custom function provider:

  1. Create an App Services function to handle your authentication needs.

  2. Enable the Custom Function Provider for your App Services App and configure it to use the function you created earlier.

  3. Destructure logInWithFunction and result from the useAuth hook.

  4. Pass any relevant user data (like a username) to logInWithFunction().

  5. Handle the result.

export const LogInWithFunction = () => {
const {logInWithFunction, result} = useAuth();
const performFunctionLogin = async (email: string, password: string) => {
// Pass arbitrary information to the Atlas function configured
// for your App's Custom Function provider.
logInWithFunction({email, password});
};
// Handle `result`...
};

El proveedor de autenticación de Facebook le permite autenticar usuarios a través de una aplicación de Facebook utilizando su cuenta de Facebook existente.

Para iniciar sesión de un usuario con una cuenta de Facebook existente, debe configurar y habilitar el proveedor de autenticación de Facebook para tu App Services App.

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.

Puedes utilizar el SDK oficial de Facebook Para gestionar la autenticación del usuario y redirigir el flujo desde una aplicación cliente. Una vez autenticado, el SDK de Facebook devuelve un token de acceso que puedes enviar a tu aplicación React Native y usar para finalizar el inicio de sesión del usuario.

export const LogInWithFacebook = () => {
const {logInWithFacebook, result} = useAuth();
const performLogin = () => {
// Get an access token using the Facebook SDK.
// You must define this function.
const token = getFacebookToken();
logInWithFacebook(token);
};
// Handle `result`...
};

The Google authentication provider allows you to authenticate users with their existing Google account.

Para autenticar a un usuario de Google, debes configurar el proveedor de autenticación de Google para tu aplicación de Servicios de aplicaciones.

There is no official Sign in With Google integration for React Native. The simplest approach to integrating Sign in With Google into your React Native app with Realm authentication is to use a third-party library. You can also build your own solution using Google Identity Services to handle the user authentication and redirect flow from a client application.

Independientemente de la implementación, debes recuperar un token de ID del servidor de autorización de Google. Úsalo para iniciar sesión en Realm.

export const LogInWithGoogle = () => {
const {logInWithGoogle, result} = useAuth();
const performLogin = () => {
// Get an access token using a third-party library
// or build your own solution. You must define this function.
const token = getGoogleToken();
logInWithGoogle(token);
};
// Handle `result`...
};

The Apple authentication provider allows you to authenticate users through Sign-in With Apple.

Para autenticar a un usuario de Apple, debes configurar el proveedor de autenticación de Apple para tu aplicación App Services.

Puedes usar el SDK oficial de Iniciar sesión con Apple JS para gestionar la autenticación del usuario y redirigir el flujo desde una aplicación cliente. Una vez autenticado, el SDK de Apple JS devuelve un token de ID que puedes enviar a tu app React Native y usar para finalizar el inicio de sesión del usuario.

export const LogInWithApple = () => {
const {logInWithApple, result} = useAuth();
const performLogin = () => {
// Get an access token using the Apple SDK.
// You must define this function.
const token = getAppleToken();
logInWithApple(token);
};
// Handle `result`...
};

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.

Cuando tu aplicación Realm autentica a un usuario, almacena en caché las credenciales del usuario. Puedes comprobar si existen credenciales de usuario para omitir el flujo de inicio de sesión y acceder al usuario almacenado en caché. Usa esto para abrir un realm sin conexión.

Nota

El inicio de sesión inicial requiere una conexión de red

Cuando un usuario se registra en tu aplicación o inicia sesión por primera vez con una cuenta existente en un cliente, este debe tener conexión de red. Comprobar las credenciales de usuario en caché permite abrir un reino sin conexión, pero solo si el usuario ha iniciado sesión previamente con conexión.

// Log user into your App Services App.
// On first login, the user must have a network connection.
const getUser = async () => {
// If the device has no cached user credentials, log in.
if (!app.currentUser) {
const credentials = Realm.Credentials.anonymous();
await app.logIn(credentials);
}
// If the app is offline, but credentials are
// cached, return existing user.
return app.currentUser!;
};

Para aprender a usar el usuario en caché en la Configuración de sincronización y acceder a un realm sin conexión, consulta los Abrir un Realm sincronizado sin conexión docs.

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:

const RefreshUserAcessToken = () => {
const user = useUser();
const [accessToken, setAccessToken] = useState<string | null>();
// Gets a valid user access token to authenticate requests
const refreshAccessToken = async () => {
// An already logged in user's access token might be stale. To
// guarantee that the token is valid, refresh it if necessary.
await user.refreshCustomData();
setAccessToken(user.accessToken);
};
// Use access token...
};

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.

If the refresh token expires after the realm is open, the device will not be able to sync until the user logs in again. Your sync error handler should implement logic that catches a token expired error when attempting to sync, then redirect users to a login flow.

For information on configuring refresh token expiration, refer to Manage User Sessions in the App Services documentation.

Para cerrar la sesión de cualquier usuario, llama al método User.logOut() en su instancia de usuario.

Advertencia

Cuando un usuario cierra su sesión, ya no puedes leer ni escribir datos en los realms sincronizados que haya abierto ese usuario. Como resultado, cualquier operación que no se haya completado antes de que el usuario que la inició cierre su sesión no podrá completarse correctamente y es probable que genere un error. Cualquier dato en una operación de escritura que falle de esta manera se perderá.

function UserInformation() {
const user = useUser();
const {logOut} = useAuth();
const performLogout = () => {
logOut();
};
// Add UI for logging out...
}

The useAuth hook has an authentication method for every App Services authentication provider. It also has state related to authentication. Refer to the useAuth reference for details.

También puedes consultar la documentación de la @realm/react API para useAuth.

Volver

Create and Delete Users