flutter_secure_auth 0.1.8
flutter_secure_auth: ^0.1.8 copied to clipboard
A secure, lightweight authentication package for Flutter (REST + OAuth2 PKCE + token refresh) with secure local storage.
flutter_secure_auth 🔒 #
A secure, lightweight, and offline-resilient authentication client for Flutter applications. It seamlessly handles OAuth2 PKCE authorization flows, REST sign-ins, secure token storage, and automatic credential refreshes with full multi-platform support (including WebAssembly/WASM).
✨ Key Features #
- 🔐 RFC 7636 OAuth2 PKCE Compliance: Safe code exchange generation using strictly compliant unreserved characters.
- ⚡ 100% WASM Compatible: Fully migrated web storage to
package:web/dart:js_interopfor next-gen Flutter Web builds. - 🔌 Offline Resiliency: Smart refresh scheduling. The package won't prematurely wipe credentials during network loss or 5xx server issues. It only logs out on definitive auth errors (400/401/403).
- 🩹 Self-Healing Storage: Corrupt secure storage inputs are silently discarded and healed, returning a clean login state rather than crashing your application.
- 💾 Secure Local Storage: Keychain (iOS/macOS), Keystore (Android), and secure desktop solutions using version 10+ storage layers.
- 🔁 Auto Token Refresh: Automatic, thread-safe request interception that checks, renews, and appends headers seamlessly.
🚀 Installation #
Add the package to your pubspec.yaml:
dependencies:
flutter_secure_auth: ^0.1.6
Then run:
flutter pub get
🧩 Usage Guide #
1. Initialize the Auth Service #
import 'package:flutter_secure_auth/flutter_secure_auth.dart';
final authService = AuthService(
tokenEndpoint: Uri.parse('https://api.yourdomain.com/oauth/token'),
revokeEndpoint: Uri.parse('https://api.yourdomain.com/oauth/revoke'), // Optional
);
2. Sign In with Password #
final tokens = await authService.signInWithPassword(
endpoint: Uri.parse('https://api.yourdomain.com/auth/login'),
username: 'user@example.com',
password: 'securePassword123',
);
print('Access Token: ${tokens.accessToken}');
3. OAuth2 PKCE Flow #
Generate a cryptographically secure verifier/challenge pair (conforming to RFC 7636) and initiate the authorization flow:
// 1. Create the PKCE pair
final pkce = createPkcePair(length: 64);
// 2. Build your authorization URL
final authUrl = Uri.parse('https://auth.yourdomain.com/authorize').replace(
queryParameters: {
'response_type': 'code',
'client_id': 'your-client-id',
'redirect_uri': 'com.yourapp:/oauthredirect',
'scope': 'openid profile offline_access',
'code_challenge': pkce.codeChallenge,
'code_challenge_method': 'S256',
'state': pkce.state,
},
);
// 3. After redirect & code capture, perform secure exchange:
final tokens = await authService.exchangeAuthorizationCode(
code: 'returned_auth_code_from_redirect',
codeVerifier: pkce.codeVerifier,
redirectUri: Uri.parse('com.yourapp:/oauthredirect'),
);
4. Send Authorized HTTP Requests #
Use the automatic request interceptor to attach authentication headers. It checks for token expiration and triggers a background refresh thread-safely before appending the header.
import 'package:http/http.dart' as http;
final rawRequest = http.Request('GET', Uri.parse('https://api.yourdomain.com/profile'));
// Automatically refreshes token if expired and appends "Authorization: Bearer <token>"
final authorizedRequest = await authService.authorizedRequest(rawRequest);
final response = await authorizedRequest.send();
final profileData = await response.stream.bytesToString();
5. Sign Out #
// Revokes refresh token server-side (if revokeEndpoint is set) and wipes local storage
await authService.signOut(revokeServerSide: true);
🎮 Interactive Playable Demo #
The package includes a comprehensive, playable Pet Supplies Store Checkout MVP demo illustrating:
- Filtering and cart management.
- Integration of
AuthServiceandTokenStorageduring checkout. - Simulated authentication states.
To run the demo, clone the repository and execute:
cd example
flutter run
📄 License #
This project is licensed under the MIT License - see the LICENSE file for details.