Realm proporciona una API para autenticar usuarios mediante cualquier proveedor de autenticación habilitado. Crear una instancia Credentials objeto y páselo a cualquiera de los métodos app.login() o app.loginAsync() para autenticar el inicio de sesión de un usuario y crear un objeto User. Cada proveedor de autenticación corresponde a un método auxiliar estático que se utiliza para instanciar objetos Credentials mediante dicho proveedor.
Iniciar sesión
You can authenticate users with either the app.login() or app.loginAsync() methods of your application's instance of the io.realm.mongodb.App class. While the app.login() method blocks code execution in the calling thread until the supplied credentials have either succeeded or failed to authenticate a user, the app.loginAsync() method allows execution to continue, handling success or failure with a callback function that is guaranteed to execute on the same thread that called app.loginAsync().
If successful, the app.login() method returns a User object. In the event of a failure, the app.login() method throws an exception of type ObjectServerError.
Pass a callback to the app.loginAsync() method to handle success or failure. This callback accepts a single parameter of type App.Result. The isSuccess() method of the App.Result object passed to the callback returns a boolean that indicates whether the operation succeeded. In the event of a failure, you can view the error that caused the failure using the getError() method.
Usuario anónimo
La El proveedor de autenticación anónima permite a los usuarios iniciar sesión en su aplicación con cuentas temporales que no almacenan información personal persistente. Para iniciar sesión con autenticación anónima, cree una credencial anónima llamando Credentials.anonymous() a y luego envíe la credencial generada a app.login() app.loginAsync()o.
String appID = YOUR_APP_ID; // replace this with your App ID App app = new App(new AppConfiguration.Builder(appID) .build()); Credentials anonymousCredentials = Credentials.anonymous(); AtomicReference<User> user = new AtomicReference<User>(); app.loginAsync(anonymousCredentials, it -> { if (it.isSuccess()) { Log.v("AUTH", "Successfully authenticated anonymously."); user.set(app.currentUser()); } else { Log.e("AUTH", it.getError().toString()); } });
val appID = YOUR_APP_ID // replace this with your App ID val app: App = App( AppConfiguration.Builder(appID) .build() ) val anonymousCredentials: Credentials = Credentials.anonymous() var user: User? app.loginAsync(anonymousCredentials) { if (it.isSuccess) { Log.v("AUTH", "Successfully authenticated anonymously.") user = app.currentUser() } else { Log.e("AUTH", it.error.toString()) } }
Email/Password User
The Email/Password authentication provider enables users to log in to your application with an email username and a password. To log in with email/password authentication, create an email/password credential by calling Credentials.emailPassword() with the user's email and password. Then pass the generated credential to app.login() or app.loginAsync().
String appID = YOUR_APP_ID; // replace this with your App ID App app = new App(new AppConfiguration.Builder(appID) .build()); Credentials emailPasswordCredentials = Credentials.emailPassword("<email>", "<password>"); AtomicReference<User> user = new AtomicReference<User>(); app.loginAsync(emailPasswordCredentials, it -> { if (it.isSuccess()) { Log.v("AUTH", "Successfully authenticated using an email and password."); user.set(app.currentUser()); } else { Log.e("AUTH", it.getError().toString()); } });
val appID = YOUR_APP_ID // replace this with your App ID val app: App = App( AppConfiguration.Builder(appID) .build() ) val emailPasswordCredentials: Credentials = Credentials.emailPassword( "<email>", "<password>" ) var user: User? = null app.loginAsync(emailPasswordCredentials) { if (it.isSuccess) { Log.v("AUTH", "Successfully authenticated using an email and password.") user = app.currentUser() } else { Log.e("AUTH", it.error.toString()) } }
API Key User
El proveedor de autenticación de clave API permite a los usuarios iniciar sesión en su aplicación con una clave API generada automáticamente en el SDK del cliente. Para iniciar sesión con autenticación de clave API, cree una credencial Credentials.apiKey() de clave API llamando a con una clave API. Luego, pase la credencial generada a app.login() app.loginAsync()o.
String appID = YOUR_APP_ID; // replace this with your App ID App app = new App(new AppConfiguration.Builder(appID) .build()); Credentials apiKeyCredentials = Credentials.apiKey("<key>"); AtomicReference<User> user = new AtomicReference<User>(); app.loginAsync(apiKeyCredentials, it -> { if (it.isSuccess()) { Log.v("AUTH", "Successfully authenticated using an API Key."); user.set(app.currentUser()); } else { Log.e("AUTH", it.getError().toString()); } });
val appID = YOUR_APP_ID // replace this with your App ID val app: App = App( AppConfiguration.Builder(appID) .build() ) val apiKeyCredentials: Credentials = Credentials.apiKey("<key>") var user: User? = null app.loginAsync(apiKeyCredentials) { if (it.isSuccess) { Log.v("AUTH", "Successfully authenticated using an API Key.") user = app.currentUser() } else { Log.e("AUTH", "Error logging in: ${it.error.toString()}") } }
Usuario JWT personalizado
El proveedor de autenticación JWT personalizada permite a los usuarios iniciar sesión en su aplicación con un token web JSON personalizado. Para iniciar sesión con autenticación JWT personalizada, cree una credencial JWT personalizada llamando Credentials.jwt() a con su JWT personalizado. Luego, pase la credencial generada a app.login() app.loginAsync()o.
String appID = YOUR_APP_ID; // replace this with your App ID App app = new App(new AppConfiguration.Builder(appID) .build()); // fetch JWT from custom provider Credentials customJWTCredentials = Credentials.jwt("<token>"); AtomicReference<User> user = new AtomicReference<User>(); app.loginAsync(customJWTCredentials, it -> { if (it.isSuccess()) { Log.v("AUTH", "Successfully authenticated using a custom JWT."); user.set(app.currentUser()); } else { Log.e("AUTH", it.getError().toString()); } });
val appID = YOUR_APP_ID // replace this with your App ID val app: App = App( AppConfiguration.Builder(appID) .build() ) // fetch JWT from custom provider val customJWTCredentials: Credentials = Credentials.jwt("<token>") var user: User? = null app.loginAsync(customJWTCredentials) { if (it.isSuccess) { Log.v("AUTH", "Successfully authenticated using a custom JWT.") user = app.currentUser() } else { Log.e("AUTH", "Error logging in: ${it.error.toString()}") } }
Usuario de función personalizada
El proveedor de autenticación de funciones personalizadas permite a los usuarios iniciar sesión en su aplicación mediante una función de Realm definida en su aplicación. Para iniciar sesión con la autenticación de función personalizada, cree una credencial llamando Credentials.customFunction() a. El método customFunction() espera un documento que contenga las propiedades y los valores utilizados por la función de autenticación de Realm. Por ejemplo, supongamos que la función de backend espera que el parámetro de entrada incluya un campo username llamado, como este:
exports = async function(loginPayload) { const { username } = loginPayload; ... }
El documento que pases a Credentials.customFunction() podría verse así:
Document("username", "bob")
Luego pasa la credencial generada a app.login() o app.loginAsync().
String appID = YOUR_APP_ID; // replace this with your App ID App app = new App(new AppConfiguration.Builder(appID).build()); Credentials customFunctionCredentials = Credentials.customFunction(new org.bson.Document("username", "bob")); AtomicReference<User> user = new AtomicReference<User>(); app.loginAsync(customFunctionCredentials, it -> { if (it.isSuccess()) { Log.v("AUTH", "Successfully authenticated using a custom function."); user.set(app.currentUser()); } else { Log.e("AUTH", it.getError().toString()); } });
val appID = YOUR_APP_ID // replace this with your App ID val app: App = App( AppConfiguration.Builder(appID) .build() ) val customFunctionCredentials: Credentials = Credentials.customFunction(org.bson.Document("username", "bob")) var user: User? = null app.loginAsync(customFunctionCredentials) { if (it.isSuccess) { Log.v("AUTH", "Successfully authenticated using a custom function.") user = app.currentUser() } else { Log.e("AUTH", "Error logging in: ${it.error.toString()}") } }
Facebook User
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.
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.
Siga la guía de inicio rápido oficial de inicio de sesión de Facebook para AndroidPara configurar el flujo de autenticación de su aplicación. En el controlador de finalización de inicio de sesión, obtenga el token de acceso del usuario conectado de Facebook LoginResult. Use el token de acceso para crear una credencial de Facebook de Realm y luego inicie la sesión del usuario en su aplicación Realm.
FacebookSdk.setApplicationId(YOUR_FACEBOOK_SDK_APP_ID); FacebookSdk.sdkInitialize(activity); CallbackManager callbackManager = CallbackManager.Factory.create(); LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() { public void onSuccess(LoginResult loginResult) { // Signed in successfully, forward credentials to MongoDB Realm. AccessToken accessToken = loginResult.getAccessToken(); Credentials facebookCredentials = Credentials.facebook(accessToken.getToken()); app.loginAsync(facebookCredentials, it -> { if (it.isSuccess()) { Log.v("AUTH", "Successfully logged in to MongoDB Realm using Facebook OAuth."); } else { Log.e("AUTH", "Failed to log in to MongoDB Realm", it.getError()); } }); } public void onCancel() { Log.v("AUTH", "Facebook authentication cancelled."); } public void onError(FacebookException exception) { Log.e("AUTH", "Failed to authenticate using Facebook: " + exception.getMessage()); } } ); LoginManager.getInstance().logIn(activity, null);
FacebookSdk.setApplicationId(YOUR_FACEBOOK_SDK_APP_ID) FacebookSdk.sdkInitialize(activity) val callbackManager = CallbackManager.Factory.create() LoginManager.getInstance().registerCallback( callbackManager, object : FacebookCallback<LoginResult> { override fun onSuccess(loginResult: LoginResult) { // Signed in successfully, forward credentials to MongoDB Realm. val accessToken = loginResult.accessToken val facebookCredentials: Credentials = Credentials.facebook(accessToken.token) app.loginAsync(facebookCredentials) { if (it.isSuccess) { Log.v( "AUTH", "Successfully logged in to MongoDB Realm using Facebook OAuth." ) } else { Log.e("AUTH", "Failed to log in to MongoDB Realm", it.error) } } } override fun onCancel() { Log.v("AUTH", "Cancelled Facebook login") } override fun onError(exception: FacebookException) { Log.e("AUTH", "Failed to authenticate with Facebook: ${exception.message}") } })
Usuario de Google
Importante
Para iniciar sesión un usuario con su cuenta de Google existente, debe configurar y habilitar el proveedor de autenticación de Google para su aplicación.
To set up your application for Google User authentication:
In the Google Cloud Platform console, create an OAuth 2.0 client ID of type "Web application".
Configure your backend App to use that client ID and the associated client secret.
Enable OpenID Connect on the backend.
Use Google's official Sign-In for Android to authenticate Google users in your Android application:
Nota
Ejemplo de código a continuación
For an implementation of these instructions, check out the code block below.
Add the Google Sign-In for Android dependency to the
dependenciesblock of your application levelbuild.gradle:com.google.android.gms:play-services-auth:19.2.0 Cree un GoogleSignInOptions con las siguientes opciones de creación:
una solicitud de ID token -- pase su OAuth 2.0 ID de cliente como el
serverClientId.
Use the
GoogleSignInOptionsto create aGoogleSignInClientwith GoogleSignIn.getClient()Use the
GoogleSignInClientto create anIntentcapable of triggering Google Sign-In.Use registerForActivityResult() to configure a callback. Your callback should use GoogleSignIn.getSignedInAccountFromIntent() to access the result of Google Sign-In: a
Task<GoogleSignInAccount>.Use the launch() method of the ActivityResultLauncher returned in the previous step to start Google Sign-In. Pass the
launch()method your Google Sign-InIntent.Utilice
isSuccessful()para gestionar los errores de inicio de sesión con Google.Accede al resultado de la tarea (una GoogleSignInAccount) con
getResult().Accede al ID token para el
GoogleSignInAccountcongetIdToken().Cree un objeto Realm
Credentialscon Credentials.google() Pasa el token de ID como primer parámetro y GoogleAuthType.ID_TOKEN como segundo parámetro.Utilice los métodos app.loginAsync() o app.login() para autenticarse con el backend de Atlas App Services usando el token.
The following code implements this flow, starting with a method call to loginWithGoogle():
private void signInWithGoogle() { GoogleSignInOptions gso = new GoogleSignInOptions .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken("YOUR WEB APPLICATION CLIENT ID FOR GOOGLE AUTH") .build(); GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, gso); Intent signInIntent = googleSignInClient.getSignInIntent(); ActivityResultLauncher<Intent> resultLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() { public void onActivityResult(ActivityResult result) { Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(result.getData()); handleSignInResult(task); } }); resultLauncher.launch(signInIntent); } private void handleSignInResult(Task<GoogleSignInAccount> completedTask) { try { if (completedTask.isSuccessful()) { GoogleSignInAccount account = completedTask.getResult(ApiException.class); String token = account.getIdToken(); Credentials googleCredentials = Credentials.google(token, GoogleAuthType.ID_TOKEN); app.loginAsync(googleCredentials, it -> { if (it.isSuccess()) { Log.v("AUTH", "Successfully logged in to MongoDB Realm using Google OAuth."); } else { Log.e("AUTH", "Failed to log in to MongoDB Realm: ", it.getError()); } }); } else { Log.e("AUTH", "Google Auth failed: " + completedTask.getException().toString()); } } catch (ApiException e) { Log.w("AUTH", "Failed to log in with Google OAuth: " + e.getMessage()); } }
fun loginWithGoogle() { val gso = GoogleSignInOptions .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken("YOUR WEB APPLICATION CLIENT ID FOR GOOGLE AUTH") .build() val googleSignInClient = GoogleSignIn.getClient(this, gso) val signInIntent: Intent = googleSignInClient.signInIntent val resultLauncher: ActivityResultLauncher<Intent> = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> val task: Task<GoogleSignInAccount> = GoogleSignIn.getSignedInAccountFromIntent(result.data) handleSignInResult(task) } resultLauncher.launch(signInIntent) } fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) { try { if (completedTask.isSuccessful) { val account: GoogleSignInAccount? = completedTask.getResult(ApiException::class.java) val token: String = account?.idToken!! val googleCredentials: Credentials = Credentials.google(token, GoogleAuthType.ID_TOKEN) app.loginAsync(googleCredentials) { if (it.isSuccess) { Log.v( "AUTH", "Successfully logged in to MongoDB Realm using Google OAuth." ) } else { Log.e("AUTH", "Failed to log in to MongoDB Realm", it.error) } } } else { Log.e("AUTH", "Google Auth failed: ${completedTask.exception}") } } catch (e: ApiException) { Log.e("AUTH", "Failed to authenticate using Google OAuth: " + e.message); } }
Tip
To learn more about Google Sign-In for Android, check out the official Google Sign-In for Android Integration Guide.
Apple User
El proveedor de autenticación Sign-in with Apple permite a los usuarios iniciar sesión en tu aplicación con un token personalizado proporcionado por Apple. Para iniciar sesión con la autenticación Sign-in with Apple, crea una credencial de Sign-in with Apple llamando a Credentials.apple() con el token proporcionado por Apple. Luego pasa la credencial generada a app.login() o app.loginAsync().
String appID = YOUR_APP_ID; // replace this with your App ID App app = new App(new AppConfiguration.Builder(appID) .build()); // fetch apple token using Apple SDK Credentials appleCredentials = Credentials.apple("<token>"); AtomicReference<User> user = new AtomicReference<User>(); app.loginAsync(appleCredentials, it -> { if (it.isSuccess()) { Log.v("AUTH", "Successfully authenticated using Sign-in with Apple."); user.set(app.currentUser()); } else { Log.e("AUTH", it.getError().toString()); } });
val appID = YOUR_APP_ID // replace this with your App ID val app: App = App( AppConfiguration.Builder(appID) .build() ) // fetch IDToken using Apple SDK val appleCredentials: Credentials = Credentials.apple("<token>") var user: User? = null app.loginAsync(appleCredentials) { if (it.isSuccess) { Log.v("AUTH", "Successfully authenticated using Sign-in with Apple.") user = app.currentUser() } else { Log.e("AUTH", "Error logging in: ${it.error.toString()}") } }
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.
Inicio de sesión sin conexión
App Services manages sessions with access tokens and refresh tokens. Client SDKs supply the logic to manage tokens, and provide them with requests.
El SDK almacena estos tokens en Preferencias compartidas.
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 the user into the backend app. // The first time you login, the user must have a network connection. String appID = YOUR_APP_ID; // replace this with your App ID App app = new App(new AppConfiguration.Builder(appID) .build()); // Check for an existing user. // If the user is offline but credentials are // cached, this returns the existing user. AtomicReference<User> user = new AtomicReference<User>(); user.set(app.currentUser()); if (user.get() == null) { // If the device has no cached user // credentials, log them in. Credentials anonymousCredentials = Credentials.anonymous(); app.loginAsync(anonymousCredentials, it -> { if (it.isSuccess()) { Log.v("AUTH", "Successfully authenticated anonymously."); user.set(app.currentUser()); } else { Log.e("AUTH", it.getError().toString()); } }); }
// Log the user into the backend app. // The first time you login, the user must have a network connection. val appID = YOUR_APP_ID // replace this with your App ID val app = App( AppConfiguration.Builder(appID) .build() ) // Check for an existing user. // If the user is offline but credentials are // cached, this returns the existing user. val user = AtomicReference<User?>() user.set(app.currentUser()) if (user.get() == null) { // If the device has no cached user // credentials, log them in. val anonymousCredentials = Credentials.anonymous() app.loginAsync( anonymousCredentials ) { it: App.Result<User?> -> if (it.isSuccess) { Log.v("AUTH", "Successfully authenticated anonymously.") user.set(app.currentUser()) } else { Log.e("AUTH", it.error.toString()) } } }
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 public String getValidAccessToken(User user) { // An already logged in user's access token might be stale. To // guarantee that the token is valid, refresh it if necessary. user.refreshCustomData(); return user.getAccessToken(); }
// Gets a valid user access token to authenticate requests fun getValidAccessToken(user: User?): String { // An already logged in user's access token might be stale. To // guarantee that the token is valid, refresh it if necessary. user!!.refreshCustomData() return user.accessToken }
Log a User Out
Puede cerrar la sesión de cualquier usuario, independientemente del proveedor de autenticación utilizado para iniciar sesión, mediante los métodos user.logOut() o user.logOutAsync(). Ambos métodos:
delete locally stored user credentials from the device
immediately halt 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.
user.get().logOutAsync( result -> { if (result.isSuccess()) { Log.v("AUTH", "Successfully logged out."); } else { Log.e("AUTH", result.getError().toString()); } });
user?.logOutAsync { if (it.isSuccess) { Log.v("AUTH", "Successfully logged out.") } else { Log.e("AUTH", it.error.toString()) } }