Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 42 ยท Data and Storage

Preferences and Secure Storage

Store settings with Preferences, secrets with SecureStorage and small objects as JSON in .NET MAUI. Learn what belongs where, with testable wrappers you can run.

Almost every app needs to remember something: the selected theme, a user name, the last opened tab, an access token. .NET MAUI offers two small key-value stores for this. Preferences is for harmless settings. SecureStorage is for secrets. Choosing the right one, and hiding both behind your own interface, makes your app safer and easier to test.

Preferences and SecureStorage use native stores (SharedPreferences, UserDefaults, Keychain, Windows ApplicationData) and cannot run in the browser. The MAUI code is read-only; the runnable examples are plain C# stand-ins for the wrappers and the logic around them.

Preferences

Preferences stores simple values by key and survives app restarts:

C#
Preferences.Default.Set("username", "Mia");
Preferences.Default.Set("launch_count", 5);
Preferences.Default.Set("dark_mode", true);
Preferences.Default.Set("last_sync", DateTime.UtcNow);

string name = Preferences.Default.Get("username", "guest");   // default if missing
int count = Preferences.Default.Get("launch_count", 0);

bool has = Preferences.Default.ContainsKey("username");
Preferences.Default.Remove("username");
Preferences.Default.Clear();

Supported types are string, bool, int, long, float, double and DateTime (plus DateTimeOffset and a few more in recent versions). Get needs a default value, which also tells MAUI the type. Because values are stored per type, reading a key with a different type than it was saved with will fail or return the default, so keep key names and types consistent.

There is also a shared container for sharing preferences between your app and an extension: Preferences.Default.Set("k", "v", "my.shared.name").

What belongs here: theme, language, "has seen the intro", last selected filter, small counters. What does not belong: passwords, tokens, lists of records or anything large. Preferences are not encrypted, and on a rooted or jailbroken device they can be read.

SecureStorage

SecureStorage keeps small strings in the platform's secure store: the Android Keystore, the iOS Keychain and Windows data protection.

C#
await SecureStorage.Default.SetAsync("oauth_token", token);

string? stored = await SecureStorage.Default.GetAsync("oauth_token");
if (stored is null)
{
    // nothing saved, ask the user to sign in
}

SecureStorage.Default.Remove("oauth_token");
SecureStorage.Default.RemoveAll();

Points to remember:

  • The API is asynchronous and values are strings only. Serialize to JSON for anything more.
  • Entries can become unreadable. On Android, a backup restore to a new device or a change to the lock screen can invalidate the key, and GetAsync may throw. Wrap calls in try/catch, and when decryption fails, delete the entry and ask the user to sign in again.
  • On iOS the Keychain may survive an uninstall. Do not assume a fresh install means empty storage.
  • Keep values small. This is not a database.
  • On Android, disable auto-backup of the secure storage file so tokens are not restored where they cannot be decrypted. The AndroidManifest.xml allows you to configure android:allowBackup.

Storing objects as JSON

Preferences take simple values, but an object is only a few lines away with System.Text.Json:

C#
public record UserSettings(string Theme, int FontSize, bool Notifications);

var settings = new UserSettings("dark", 16, true);
Preferences.Default.Set("settings", JsonSerializer.Serialize(settings));

string json = Preferences.Default.Get("settings", "");
UserSettings loaded = json.Length > 0
    ? JsonSerializer.Deserialize<UserSettings>(json)!
    : new UserSettings("light", 14, false);

If the object grows beyond a few settings, move it to a file or a database (files and JSON, SQLite).

Wrap storage behind an interface

If view models call Preferences.Default directly, you cannot unit test them without a device. Define an interface in shared code and implement it once with the MAUI API:

C#
public interface ISettingsStore
{
    T Get<T>(string key, T defaultValue);
    void Set<T>(string key, T value);
}

public class MauiSettingsStore : ISettingsStore
{
    public T Get<T>(string key, T defaultValue) => Preferences.Default.Get(key, defaultValue);
    public void Set<T>(string key, T value) => Preferences.Default.Set(key, value);
}

Register it with builder.Services.AddSingleton<ISettingsStore, MauiSettingsStore>(); and inject it. Tests then use an in-memory implementation, which is what we build next.

Try it: an in-memory settings store with JSON objects

C# Stand-in: ISettingsStore

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The stand-in stores everything as text, which is how most native stores work underneath.

Try it: handling a secure store that fails

Secure storage can throw when the key was invalidated. A good token service treats that as "signed out" rather than crashing. This stand-in simulates the failure with a fake store.

C# Stand-in: a token service that survives bad storage

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Which store should I use?

Pick the right place

Preferences Small, harmless settings
SecureStorage Tokens and secrets
A file Documents and cached data
SQLite Lists of records

Never put a secret in Preferences.

1 / 2

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which is the right place to store an OAuth refresh token?

    SecureStorage uses the Keystore or Keychain; Preferences are not encrypted.
  2. 2. Why does Preferences.Default.Get require a default value?

    The default is returned when the key does not exist, and its type determines how the stored value is read.
  3. 3. What should you do if SecureStorage.GetAsync throws because the key is no longer valid?

    An unreadable entry cannot be recovered, so clear it and restart the sign-in flow.
  4. 4. Why put an ISettingsStore interface in front of Preferences?

    An interface lets tests supply an in-memory fake instead of the native store.

Summary

  • Preferences is for small, non-secret settings; SecureStorage is for secrets.
  • Values are simple types (preferences) or strings (secure storage); serialize objects to JSON.
  • Expect secure storage to fail sometimes, and recover by signing the user out.
  • Hide both behind interfaces so view models stay testable.

Next: Files and JSON