A simple and flexible authentication library for Dart applications supporting multiple OAuth providers with type-safe provider management.
- π OAuth 2.0 authentication
- π Multiple provider support (GitHub, Google)
- π¦ Easy integration with singleton pattern
- π― Type-safe API with Provider enum
- π State management with configurable expiration
- π‘οΈ Built-in error handling and validation
- GitHub - Complete OAuth flow with user profile and email
- Google - OpenID Connect with profile information
Add this to your pubspec.yaml:
dependencies:
authx: ^1.0.2Then run:
dart pub getimport 'package:authx/authx.dart';
void main() async {
// 1. Configure AuthX singleton with providers (call once)
AuthX.configure(
expiration: Duration(minutes: 30),
providers: {
'github': GitHubProvider(
clientId: 'your_github_client_id',
clientSecret: 'your_github_client_secret',
redirectUri: 'http://localhost:8080/api/v1/auth/github/callback',
),
'google': GoogleProvider(
clientId: 'your_google_client_id',
clientSecret: 'your_google_client_secret',
redirectUri: 'http://localhost:8080/api/v1/auth/google/callback',
),
},
);
// 2. Get the singleton instance
final authX = AuthX.instance;
// 3. Get authorization URL (redirect user to this URL)
final authUrl = authX.getAuthorizationUrl(Provider.github);
print('Redirect user to: $authUrl');
// 4. Handle callback and get user profile
try {
final profile = await authX.handleCallback(
providerId: Provider.github,
query: {
'code': 'authorization_code_from_callback',
'state': 'state_from_auth_url',
},
);
print('β Authentication successful!');
print('User email: ${profile.email}');
print('User name: ${profile.name}');
print('Avatar: ${profile.avatar}');
print('Provider: ${profile.provider}');
} on DartAuthException catch (e) {
print('β Authentication failed: ${e.message}');
print('Error code: ${e.code}');
}
}Type-safe provider identification:
enum Provider {
github,
google;
String get value; // Returns string representation
static Provider fromString(String value); // Convert string to enum
}Main authentication manager with singleton pattern.
AuthX.configure({
Duration? expiration, // State expiration time (default: 5 minutes)
Map<String, OAuthProvider>? providers, // Provider configuration
});AuthX.instance- Get singleton instancegetAuthorizationUrl(Provider providerId)- Generate auth URL with statehandleCallback({Provider providerId, Map<String, String> query})- Process callbackregisterProvider(Provider id, OAuthProvider provider)- Register additional providerisStateValid(String state)- Validate state without consuming itcleanStates()- Remove expired states
User profile returned after successful authentication:
class OAuthProfile {
final String providerId; // Provider ID as string
final String email; // User email (always present)
final String? name; // User display name
final String? avatar; // Profile avatar URL
final String? provider; // Provider name as string
final Map<String, dynamic> raw; // Raw provider response
}Built-in exception types for comprehensive error handling:
try {
final profile = await authX.handleCallback(...);
} on DartAuthException catch (e) {
print('Error: ${e.message}');
print('Code: ${e.code}');
// Common error codes:
// - NOT_CONFIGURED: AuthX not configured
// - ALREADY_CONFIGURED: AuthX already configured
// - INVALID_CALLBACK_PARAMS: Missing code or state
// - INVALID_OR_EXPIRED_STATE: State invalid or expired
// - PROVIDER_NOT_FOUND: Provider not registered
// - TOKEN_EXCHANGE_FAILED: OAuth token exchange failed
// - PROFILE_FETCH_FAILED: Failed to fetch user profile
// - MISSING_EMAIL: Email not available in profile
}GitHubProvider(
clientId: 'your_client_id',
clientSecret: 'your_client_secret',
redirectUri: 'http://localhost:8080/api/v1/auth/github/callback',
)Required OAuth App Settings:
- Authorization callback URL:
http://localhost:8080/api/v1/auth/github/callback - Scopes requested:
user:email
GoogleProvider(
clientId: 'your_client_id',
clientSecret: 'your_client_secret',
redirectUri: 'http://localhost:8080/api/v1/auth/google/callback',
)Required OAuth App Settings:
- Authorized redirect URI:
http://localhost:8080/api/v1/auth/google/callback - Scopes requested:
openid email profile
// Configure custom expiration
AuthX.configure(
expiration: Duration(hours: 1), // Longer state validity
providers: providers,
);
// Validate state without consuming
if (authX.isStateValid(state)) {
// State is valid
}
// Clean up expired states
authX.cleanStates();final authX = AuthX.instance;
// Register additional providers after configuration
authX.registerProvider(
Provider.github,
GitHubProvider(/* config */),
);
authX.registerProvider(
Provider.google,
GoogleProvider(/* config */),
);For testing purposes, you can reset the AuthX configuration:
// Reset singleton (for testing only)
AuthX.reset();See the example directory for complete working examples:
- Basic OAuth Flow - Complete authentication example
- State Management: States automatically expire to prevent replay attacks
- Secret Management: Never commit client secrets to version control
- Redirect URIs: Ensure redirect URIs match your OAuth app configuration
- HTTPS: Always use HTTPS in production environments
- State Validation: Always validate the state parameter in callbacks
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
MIT License - see the LICENSE file for details.