For AI agents: A markdown version of this page is available at https://docs.datadoghq.com/security/code_security/static_analysis/static_analysis_rules/dart-security/insecure-shared-preferences.md. A documentation index is available at /llms.txt.

Avoid storing sensitive data in SharedPreferences

This product is not supported for your selected Datadog site. ().

Metadata

ID: dart-security/insecure-shared-preferences

Language: Dart

Severity: Warning

Category: Security

CWE: 922

Related CWEs:

Description

SharedPreferences stores data in an unencrypted file on the device. Storing sensitive values such as passwords, tokens, or secrets there exposes them to any app on a rooted or compromised device.

Use flutter_secure_storage to protect values that must persist on-device.

Non-Compliant Code Examples

import 'package:shared_preferences/shared_preferences.dart';

Future<void> savePassword(String password) async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.setString('password', password);
}
import 'package:shared_preferences/shared_preferences.dart';

Future<void> saveSession(String token, String refreshToken) async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.setString('auth_token', token);
  await prefs.setString('refresh_token', refreshToken);
}
import 'package:shared_preferences/shared_preferences.dart';

void cacheSecret(SharedPreferences prefs, String secret) {
  prefs.setString('secret', secret);
}

Compliant Code Examples

import 'package:flutter_secure_storage/flutter_secure_storage.dart';

Future<void> saveCredentials(String token) async {
  const storage = FlutterSecureStorage();
  await storage.write(key: 'auth_token', value: token);
}
import 'package:shared_preferences/shared_preferences.dart';

Future<void> saveSettings(String theme, bool darkMode) async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.setString('theme', theme);
  await prefs.setBool('dark_mode', darkMode);
}
import 'package:shared_preferences/shared_preferences.dart';

// Safe key, sensitive-looking hardcoded value — must not flag (key is what matters)
Future<void> saveTheme(SharedPreferences prefs) async {
  await prefs.setString('theme', 'token_value');
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security