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

Autenticar usuarios - Swift SDK

Si lo has habilitado Autenticación anónima en la interfaz de usuario de App Services: los usuarios pueden iniciar sesión inmediatamente en la aplicación sin proporcionar información de identificación. El siguiente código muestra cómo hacerlo:

let anonymousCredentials = Credentials.anonymous
app.login(credentials: anonymousCredentials) { (result) in
switch result {
case .failure(let error):
print("Login failed: \(error.localizedDescription)")
case .success(let user):
print("Successfully logged in as user \(user)")
// Now logged in, do something with user
// Remember to dispatch to main if you are doing anything on the UI thread
}
}

Si has activado la autenticación por correo electrónico/contraseña, puedes iniciar sesión utilizando el siguiente código:

let email = "skroob@example.com"
let password = "12345"
app.login(credentials: Credentials.emailPassword(email: email, password: password)) { (result) in
switch result {
case .failure(let error):
print("Login failed: \(error.localizedDescription)")
case .success(let user):
print("Successfully logged in as user \(user)")
// Now logged in, do something with user
// Remember to dispatch to main if you are doing anything on the UI thread
}
}

Si ha activado autenticación con claves API, puede iniciar sesión utilizando el siguiente código:

let credentials = Credentials.userAPIKey("<api-key>")
app.login(credentials: credentials) { (result) in
switch result {
case .failure(let error):
print("Login failed: \(error.localizedDescription)")
case .success(let user):
print("Successfully logged in as user \(user)")
// Now logged in, do something with user
// Remember to dispatch to main if you are doing anything on the UI thread
}
}

Si has habilitado el Proveedor de autenticación Función personalizada, puedes iniciar sesión con el siguiente código:

let params: Document = ["username": "bob"]
app.login(credentials: Credentials.function(payload: params)) { (result) in
switch result {
case .failure(let error):
print("Login failed: \(error.localizedDescription)")
case .success(let user):
print("Successfully logged in as user \(user)")
// Now logged in, do something with user
// Remember to dispatch to main if you are doing anything on the UI thread
}
}

Si tienes habilitado el proveedor de autenticación JWT personalizado, puedes iniciar sesión utilizando el siguiente código:

let credentials = Credentials.jwt(token: "<jwt>")
app.login(credentials: credentials) { (result) in
switch result {
case .failure(let error):
print("Login failed: \(error.localizedDescription)")
case .success(let user):
print("Successfully logged in as user \(user)")
// Now logged in, do something with user
// Remember to dispatch to main if you are doing anything on the UI thread
}
}

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 oficial de inicio de sesión rápido de Facebook para iOSPara configurar el flujo de autenticación de su aplicación, en el controlador de inicio de sesión, cree una credencial de Facebook de App Services con la cadena de token de acceso del usuario que inició sesión e inicie sesión en su aplicación de App Services.

// This example demonstrates login logic for FBSDK version 13.x. If you're using
// a different version of FBSDK, you'll need to adapt this example for your version.
let loginManager = LoginManager()
loginManager.logIn(permissions: [ .email ]) { loginResult in
switch loginResult {
case .success(let grantedPermissions, let declinedPermissions, let accessToken):
let credentials = Credentials.facebook(accessToken: accessToken!.tokenString)
app.login(credentials: credentials) { result in
DispatchQueue.main.async {
switch result {
case .failure(let error):
print("Failed to log in to MongoDB Realm: \(error)")
case .success(let user):
print("Successfully logged in to MongoDB Realm using Facebook OAuth.")
// Now logged in, do something with user
// Remember to dispatch to main if you are doing anything on the UI thread
}
}
}
case .failed(let error):
print("Facebook login failed: \(error)")
case .cancelled:
print("The user cancelled the login flow.")
}
}

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.

Sigue la Guía oficial de integración de Google Sign-In para iOS para configurar el flujo de autenticación de tu aplicación. En el controlador de finalización de inicio de sesión, crea una credencial de Google de App Services e inicia la sesión del usuario en tu aplicación de App Services.

El valor que pase a la credencial dependerá de si ha habilitado o no OpenID Connect para el proveedor:

  • Si OpenID Connect está habilitado, pase el id_token incluido en la respuesta de Google OAuth a Credentials.googleId(token:).

  • If OpenID Connect is not enabled, pass the user's server auth code to Credentials.google(serverAuthCode:).

func sign(_ signIn: GIDSignIn!, didSignInFor googleUser: GIDGoogleUser!, withError error: Error!) {
if let error = error {
print("\(error.localizedDescription)")
return
}
// Get the ID token for the authenticated user so you can pass it to Realm
let idToken = googleUser.authentication.idToken!
let credentials = Credentials.googleId(token: idToken)
app.login(credentials: credentials) { result in
DispatchQueue.main.async {
switch result {
case .failure(let error):
print("Failed to log in to MongoDB Realm: \(error)")
case .success(let user):
print("Successfully logged in to MongoDB Realm using Google OAuth.")
// Now logged in, do something with user
// Remember to dispatch to main if you are doing anything on the UI thread
}
}
}
}
func sign(_ signIn: GIDSignIn!, didSignInFor googleUser: GIDGoogleUser!, withError error: Error!) {
if let error = error {
print("\(error.localizedDescription)")
return
}
// Upon first successful sign-in, forward serverAuthCode credentials to MongoDB Realm.
// Upon subsequent sign-ins, this returns nil.
let credentials = Credentials.google(serverAuthCode: googleUser.serverAuthCode!)
app.login(credentials: credentials) { result in
DispatchQueue.main.async {
switch result {
case .failure(let error):
print("Failed to log in to MongoDB Realm: \(error)")
case .success(let user):
print("Successfully logged in to MongoDB Realm using Google OAuth.")
// Now logged in, do something with user
// Remember to dispatch to main if you are doing anything on the UI thread
}
}
}
}

If you have enabled Sign-in with Apple authentication, you can log in using the following code:

// Fetch IDToken via the Apple SDK
let credentials = Credentials.apple(idToken: "<token>")
app.login(credentials: credentials) { (result) in
switch result {
case .failure(let error):
print("Login failed: \(error.localizedDescription)")
case .success(let user):
print("Successfully logged in as user \(user)")
// Now logged in, do something with user
// Remember to dispatch to main if you are doing anything on the UI thread
}
}

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.

New in version 10.15.0.

The async/await version of the App.login method asynchronously returns a User or Error.

func login() async {
do {
let app = App(id: YOUR_APP_SERVICES_APP_ID)
// Authenticate with the instance of the app that points
// to your backend. Here, we're using anonymous login.
let user = try await app.login(credentials: Credentials.anonymous)
print("Successfully logged in user: \(user)")
} catch {
print("Failed to log in user: \(error.localizedDescription)")
}
}

Starting with Realm Swift SDK Versions 10.15.0 and 10.16.0, many of the Realm APIs support the Swift async/await syntax. Projects must meet these requirements:

Versión del SDK de Swift
Swift Version Requirement
Supported OS

10.25.0

Swift 5.6

iOS 13.x

10.15.0 o 10.16.0

Swift 5.5

iOS 15.x

If your app accesses Realm in an async/await context, mark the code with @MainActor to avoid threading-related crashes.

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.
func getUser() async throws -> User {
// Check for an existing user.
// If the user is offline but credentials are
// cached, this returns the existing user.
if let user = app.currentUser {
return user
} else {
// If the device has no cached user
// credentials, log them in.
let app = App(id: YOUR_APP_SERVICES_APP_ID)
let loggedInUser = try await app.login(credentials: Credentials.anonymous)
return loggedInUser
}
}
let user = try await getUser()
var configuration = user.configuration(partitionValue: "Some Partition Value")
// Open a Realm with this configuration.
// If you do not require the app to download updates
// before opening the realm, the realm just opens, even if
// offline.
let realm = try await Realm(configuration: configuration)
print("Successfully opened realm: \(realm)")

El SDK de Realm gestiona automáticamente los tokens de acceso, los renueva cuando caducan e incluye un token de acceso válido para el usuario actual con cada solicitud.

Si envía solicitudes fuera del SDK, debe incluir el token de acceso del usuario en cada solicitud. En este caso, debe actualizar el token manualmente cuando caduque. Los tokens de acceso caducan después de 30 minutos.

Puedes llamar a .refreshCustomData() en un usuario que ha iniciado sesión para actualizar la sesión de autenticación del usuario. Luego, devuelve el .accessToken como un string que puedes utilizar en tu código. Podrías usar una función similar a esta para obtener un access token:

func getValidAccessToken(user: User) async throws -> String {
// An already logged in user's access token might be stale. To
// guarantee that the token is valid, refresh it if necessary.
try await user.refreshCustomData()
return user.accessToken!
}

Which requires a logged-in user:

let app = App(id: YOUR_APP_SERVICES_APP_ID)
let user = try await app.login(credentials: Credentials.anonymous)
let accessToken = try await getValidAccessToken(user: user)

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.

Once logged in, you can log out:

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á.

app.currentUser?.logOut { (error) in
// user is logged out or there was an error
}

Volver

Create and Delete Users

En esta página