
# SecretTemplate

`SecretTemplate` is a bean that keeps the app's own secrets in the platform's secure storage, the same store the login keeps its tokens in. It writes objects as JSON with the application's `ObjectMapper`, under its namespace (`app.` by default), so the app's keys never meet the login's (`oauth2.`). It is shaped like Spring Vault's `VaultTemplate` (secrets by path) and `RedisTemplate` (objects through a serializer).

## Why

A PIN, an API key or the key of an encrypted database belongs in the Keychain or the Keystore, not in shared preferences. The `SecretStore` keeps strings by key; the template adds objects, JSON and a namespace, so the app writes `secrets.write('pin', settings)` and nothing more.

## Example

```dart
@Introspected()
class PinSettings {
  const PinSettings({required this.hash, required this.attempts});

  final String hash;
  final int attempts;
}

@Service()
class Pin {
  Pin(this._secrets);

  final SecretTemplate _secrets;

  Future<void> save(String hash) =>
      _secrets.write('pin', PinSettings(hash: hash, attempts: 0));

  Future<PinSettings?> current() => _secrets.read<PinSettings>('pin');

  Future<void> forget() => _secrets.delete('pin');
}
```

## The methods

| Method | Meaning |
|---|---|
| `write(key, value)` | Writes an object as JSON under the template's namespace |
| `read<T>(key)` | Reads it back; `null` when missing |
| `delete(key)` | Deletes it |
| `keys()` | The template's keys |
| `deleteAll()` | Removes the template's keys; the store's own `deleteAll()` removes everything, the login's tokens too |

## Limits

- **Small secrets, not data.** Each value is a Keychain item, an encrypted preference, a file or a keyring entry: no database, and every call is slow. To protect much data (a local database, files), encrypt it and keep only its encryption key here.
- **No web.** A browser has no secure storage, so on the web every call fails with an `UnsupportedError` (in the returned `Future`); it never falls back to memory or `localStorage`. There the server keeps secrets.
- **Replaceable.** Declare a `SecretTemplate` or a `SecretStore` bean to replace them.

## In Spring (Java)

Spring Vault's `VaultTemplate` keeps secrets by path on a Vault server; here the vault is the device's secure storage.

## See also

- [Tokens and the login window](tokens-and-login-window.md)
- [Files of the app](../spring-boot-starter-flutter/files.md)
