Atlas App Services proporciona una API para autenticar usuarios mediante cualquier proveedor de autenticación habilitado. Cree una instancia de credencialesy pasarlo a App.logIn() para autenticar y crear un objeto Usuario para ese usuario. Cada proveedor de autenticación corresponde a un método constructor estático utilizado para instanciar Credentials objetos para ese proveedor de autenticación.
Antes de comenzar
Enable and configure one or more App Services authentication providers.
Register a New User Account
Realm registers accounts differently depending on the authentication provider:
No es necesario registrar usuarios anónimos.
Para registrar un usuario de correo electrónico y contraseña, consulte Registro de usuario de correo electrónico y contraseña.
If you are using Google, Facebook, Apple, or Custom JWT authentication, registration is handled by these third-party services.
Iniciar sesión
You can authenticate users with App.logIn().
If successful, app.logIn returns a User object.
Usuario anónimo
The anonymous authentication provider enables users to log in to your application with short-term accounts that store no persistent personal information. To log in with anonymous authentication, create an anonymous credential by calling Credentials.anonymous() and then pass the generated credential to app.logIn.
final anonCredentials = Credentials.anonymous(); await app.logIn(anonCredentials);
If you want more than one anonymous user, set reuseCredentials: false when creating additional anonymous credentials.
final anonUser = await app.logIn(Credentials.anonymous()); final otherAnonUser = await app.logIn(Credentials.anonymous(reuseCredentials: false));
Email/Password User
El proveedor de autenticación por correo electrónico/clave permite a los usuarios iniciar sesión en tu aplicación con un nombre de usuario de correo electrónico y una clave. Para iniciar sesión con autenticación de correo electrónico/clave, crea una credencial de correo electrónico/clave llamando a Credentials.emailPassword() con el correo electrónico y clave del usuario. Luego, pasa la credencial a app.logIn.
final emailPwCredentials = Credentials.emailPassword("lisa@example.com", "myStr0ngPassw0rd"); await app.logIn(emailPwCredentials);
Para saber más sobre el flujo completo de uso de la autenticación de correo electrónico/contraseña de App Services, consulta Usuarios de correo/contraseña.
Usuario JWT personalizado
If you have configured the Custom JWT authentication provider, you can log in using JWT credentials from an external authentication provider.
To log in with Custom JWT authentication, create a JWT credential by calling Credentials.jwt() on a JWT string. Then pass the credential to app.logIn.
final token = await authenticateWithExternalSystem(); final jwtCredentials = Credentials.jwt(token); final currentUser = await app.logIn(jwtCredentials);
API Key User
Si ha habilitado la autenticación de clave API, puede iniciar sesión usando una clave API de cliente o de servidor.
To log in with API key authentication, create an ApiKey credential by calling Credentials.apiKey() on an API key string. Then pass the credential to app.logIn().
final apiKeyCredentials = Credentials.apiKey(myApiKey); final apiKeyUser = await app.logIn(apiKeyCredentials);
Para generar una clave API de servidor para utilizar en tus credenciales, consulta la documentación Crear una clave API de servidor.
To work with user API keys with the same permissions as the currently logged in user, use the User.apiKeys client. You can create, fetch, delete, disable, and enable user API keys.
// Create user API key final apiKey = await user.apiKeys.create("api-key-name"); // Get existing user API key by ID // Returns `null` if no existing API key for the ID final refetchedApiKey = await user.apiKeys.fetch(apiKey.id); // Get all API keys for a user final apiKeys = await user.apiKeys.fetchAll(); // Disable API key await user.apiKeys.disable(apiKey.id); // Check if API key is enabled print(apiKey.isEnabled); // prints `false` // Enable API key await user.apiKeys.enable(apiKey.id); // Delete a user API key await user.apiKeys.delete(apiKey.id);
Usuario de función personalizada
If you have configured the Custom Function authentication provider, you can log in using custom authentication logic handled by an Atlas Function.
To log in with Custom Function authentication, pass a stringified JSON with your custom arguments to Credentials.function(). Then pass the credential to app.logIn.
final credentials = { "username": "someUsername", }; // payload must be a JSON-encoded string final payload = jsonEncode(credentials); final customCredentials = Credentials.function(payload); final currentUser = await app.logIn(customCredentials);
Facebook User
If you have configured the Facebook authentication provider, you can log in using an existing Facebook account.
To log in with Facebook authentication, pass a Facebook access token to Credentials.facebook(). Then pass the credential to app.logIn.
final facebookCredentials = Credentials.facebook(accessToken); final currentUser = await app.logIn(facebookCredentials);
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.
Usuario de Google
If you have configured the Google authentication provider, you can log in using an existing Google account.
To log in with a Google authentication code, pass a Google authentication code to Credentials.googleAuthCode(). Then pass the credential to app.logIn.
final googleAuthCodeCredentials = Credentials.googleAuthCode(authCode); final currentUser = await app.logIn(googleAuthCodeCredentials);
To log in with a Google ID token, pass a Google ID token to Credentials.googleIdToken(). Then pass the credential to app.logIn.
final googleIdTokenCredentials = Credentials.googleIdToken(idToken); final currentUser = await app.logIn(googleIdTokenCredentials);
Apple User
If you have configured the Sign-in with Apple authentication provider, you can log in using an existing Apple account.
To log in with Apple authentication, pass an Apple access token to Credentials.apple(). Then pass the credential to app.logIn.
final appleCredentials = Credentials.apple(idToken); final currentUser = await app.logIn(appleCredentials);
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.
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.
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.
Log a User Out
You can log out any user, regardless of the authentication provider used to log in, using User.logOut(). This method:
Elimina las credenciales de usuario almacenadas localmente del dispositivo
Immediately halts any synchronization to and from the user's realms
Because logging out halts synchronization, you should only log out after all local Realm updates have uploaded to the server.
await user.logOut();
Retrieve Current User
Once you have an authenticated user, you can retrieve the User object with the App.currentUser property. The currentUser object is persisted in local storage, so even if the app shuts down after the initial authentication, you do not need to call logIn again (unless the user logged out).
final user = app.currentUser;