Navigation

Authenticate Users - iOS SDK

If you have enabled Anonymous authentication in the Realm UI, users can immediately log into your app without providing any identifying information. The following code shows how to do this:

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
}
}

If you have enabled Email/Password authentication, you can log in using the following code:

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
}
}

If you have enabled API Key authentication, you can log in using the following code:

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
}
}

If you have enabled the Custom Function authentication provider, you can log in using the following code:

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
}
}

If you have enabled the Custom JWT authentication provider, you can log in using the following code:

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
}
}

The Facebook authentication provider allows you to authenticate users through a Facebook app using their existing Facebook account.

Important
Enable the Facebook Auth Provider

To log a user in with their existing Facebook account, you must configure and enable the Facebook authentication provider for your application.

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

Follow the official Facebook Login for iOS Quickstart to set up the authentication flow for your application. In the login completion handler, create a Realm Facebook credential with the logged in user's access token string and log the user into your Realm app.

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.")
}
}
Important

To log a user in with their existing Google account, you must configure and enable the Google authentication provider for your application.

Follow the official Google Sign-In for iOS Integration Guide to set up the authentication flow for your application. In the sign-in completion handler, create a Realm Google credential and log the user into your Realm app.

The value that you pass to the credential depends on whether or not you have enabled OpenID Connect for the provider:

func sign(_ signIn: GIDSignIn!, didSignInFor googleUser: GIDGoogleUser!, withError error: Error!) {
if let error = error {
if (error as NSError).code == GIDSignInErrorCode.hasNoAuthInKeychain.rawValue {
print("The user has not signed in before or they have since signed out.")
} else {
print("\(error.localizedDescription)")
}
return
}
// Signed in successfully, forward credentials to MongoDB Realm.
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
}
}

Once logged in, you can log out:

Warning

When a user logs out, you can no longer read or write data in any synced realms that the user opened. As a result, any operation that has not yet completed before the initiating user logs out cannot complete successfully and will likely result in an error. Any data in a write operation that fails in this way will be lost.

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