Docs Menu

Docs HomeDevelop ApplicationsAtlas Device SDKs

Authenticate Users - .NET SDK

On this page

  • Log In
  • Anonymous User
  • Email/Password User
  • API Key User
  • Custom JWT User
  • Custom Function User
  • Facebook User
  • Google User
  • Apple User
  • Offline Login
  • Log a User Out
  • Retrieve the Current User
  • Get a User Access Token
  • Refresh Token Expiration
  • Observe Authentication Changes

The SDK provides an API for authenticating users using any enabled authentication provider. Instantiate a Credentials object and pass it to the LogInAsync() method to authenticate and obtain a User instance. The Credentials class exposes factory methods that correspond to each of the authentication providers:

Before you can authenticate a user, ensure you have:

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

var user = await app.LogInAsync(Credentials.Anonymous());

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

var user = await app.LogInAsync(
Credentials.EmailPassword("caleb@mongodb.com", "MySekritPwd"));

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

var user = await app.LogInAsync(Credentials.ApiKey(apiKey));

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

var user =
await app.LogInAsync(Credentials.JWT(jwt_token));

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

var functionParameters = new
{
username = "caleb",
password = "MySekritPwd",
IQ = 42,
hasPets = true
};
var user =
await app.LogInAsync(Credentials.Function(functionParameters));

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.

var user =
await app.LogInAsync(Credentials.Facebook(facebookToken));

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

var user =
await app.LogInAsync(Credentials.Google(googleAuthCode, GoogleCredentialType.AuthCode));

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

var user =
await app.LogInAsync(Credentials.Apple(appleToken));

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.

When your Realm application authenticates a user, it caches the user's credentials. You can check for existing user credentials to bypass the login flow and access the cached user. Use this to open a realm offline.

Note

Initial login requires a network connection

When a user signs up for your app, or logs in for the first time with an existing account on a client, the client must have a network connection. Checking for cached user credentials lets you open a realm offline, but only if the user has previously logged in while online.

The following example checks if there is a cached User object. If not, it logs the user in. Otherwise, it uses the cached credentials:

if (app.CurrentUser == null)
{
// App must be online for user to authenticate
user = await app.LogInAsync(
Credentials.EmailPassword("caleb@mongodb.com", "MySekritPwd"));
config = new PartitionSyncConfiguration("_part", user);
realm = await Realm.GetInstanceAsync(config);
}
else
{
// This works whether online or offline
user = app.CurrentUser;
config = new PartitionSyncConfiguration("_part", user);
realm = Realm.GetInstance(config);
}

Once logged in, you can log out by calling the LogOutAsync() method:

await user.LogOutAsync();

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.

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 LoginAsync again (unless the user logged out). Instead, use Realm.GetInstance(config), where config is a PartitionSyncConfiguration object. This approach results in a faster start-up and also enables the user to work offline.

When a user logs in, Atlas App Services creates an access token for the user that grants them access to your App. The Realm SDK automatically manages access tokens, refreshes them when they expire, and includes a valid access token for the current user with each request. Realm does not automatically refresh the refresh token. When the refresh token expires, the user must log in again.

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.

You can access and refresh a logged in user's access token in the SDK from their Realm.User object, as in the following example:

// Returns a valid user access token to authenticate requests
public async Task<string> GetValidAccessToken(User user)
{
// An already logged in user's access token might be stale. To
// guarantee that the token is valid, refresh it.
await user.RefreshCustomDataAsync();
return user.AccessToken;
}

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.

New in version v11.6.0.

You can observe a flow of authentication change events by calling User.Changed() on a valid user object.

Currently, User.Changed() triggers on all user events and you should add a handler to ensure your responses to events are idempotent.

app.CurrentUser.Changed += (change, _) =>
{
Debug.WriteLine($"Auth change: {change}, {_}");
};
← Create and Delete Users - .NET SDK