Skip to content

A Dart package for generating HTTP Basic Authentication headers from username and password

License

Notifications You must be signed in to change notification settings

flutterpilot/fpd_basic_auth_generator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

fpd_basic_auth_generator

Pub Version Dart CI License: MIT

A Dart package for generating HTTP Basic Authentication headers from username and password.

πŸ” Features

  • βœ… Generate Basic Auth headers: Convert username/password to HTTP headers
  • βœ… Decode headers: Extract username/password from existing headers
  • βœ… Validate headers: Check if headers are valid Basic Auth format
  • βœ… Generate commands: Create cURL and JavaScript code with authentication
  • βœ… Error handling: Comprehensive error handling with Result types
  • βœ… Unicode support: Handle special characters and Unicode in credentials
  • βœ… Round-trip conversion: Encode and decode without data loss

πŸ“¦ Installation

Add this to your package's pubspec.yaml file:

dependencies:
  fpd_basic_auth_generator: ^1.0.0

Then run:

dart pub get

πŸš€ Quick Start

import 'package:fpd_basic_auth_generator/fpd_basic_auth_generator.dart';

void main() {
  // Generate Basic Auth header
  final result = FpdBasicAuthGenerator.generateHeader('user', 'pass');
  if (result.isSuccess) {
    print(result.data!.header); // Authorization: Basic dXNlcjpwYXNz
  }
  
  // Decode existing header
  final decodeResult = FpdBasicAuthGenerator.decodeHeader('Authorization: Basic dXNlcjpwYXNz');
  if (decodeResult.isSuccess) {
    print('Username: ${decodeResult.data!.username}'); // user
    print('Password: ${decodeResult.data!.password}'); // pass
  }
}

πŸ“š API Reference

Core Methods

generateHeader(String username, String password)

Generates a complete HTTP Basic Authentication header.

final result = FpdBasicAuthGenerator.generateHeader('admin', 'secret123');
if (result.isSuccess) {
  print(result.data!.header); // Authorization: Basic YWRtaW46c2VjcmV0MTIz
  print(result.data!.base64Credentials); // YWRtaW46c2VjcmV0MTIz
  print(result.data!.username); // admin
  print(result.data!.password); // secret123
}

generateCredentials(String username, String password)

Generates only the Base64 credentials part.

final result = FpdBasicAuthGenerator.generateCredentials('user', 'pass');
if (result.isSuccess) {
  print(result.data); // dXNlcjpwYXNz
}

decodeHeader(String header)

Decodes a complete Basic Auth header to extract username and password.

final result = FpdBasicAuthGenerator.decodeHeader('Authorization: Basic dXNlcjpwYXNz');
if (result.isSuccess) {
  print('Username: ${result.data!.username}'); // user
  print('Password: ${result.data!.password}'); // pass
}

decodeCredentials(String base64Credentials)

Decodes Base64 credentials to extract username and password.

final result = FpdBasicAuthGenerator.decodeCredentials('dXNlcjpwYXNz');
if (result.isSuccess) {
  print('Username: ${result.data!.username}'); // user
  print('Password: ${result.data!.password}'); // pass
}

Validation Methods

isValidHeader(String header)

Checks if a string is a valid Basic Auth header.

final isValid = FpdBasicAuthGenerator.isValidHeader('Authorization: Basic dXNlcjpwYXNz');
print(isValid); // true

isValidCredentials(String base64Credentials)

Checks if a string is valid Base64 credentials.

final isValid = FpdBasicAuthGenerator.isValidCredentials('dXNlcjpwYXNz');
print(isValid); // true

Command Generation

generateCurl(String url, String username, String password, {String method = 'GET'})

Generates a cURL command with Basic Auth.

final result = FpdBasicAuthGenerator.generateCurl(
  'https://api.example.com/data',
  'user',
  'pass',
  method: 'POST',
);
if (result.isSuccess) {
  print(result.data);
  // curl -X POST -H "Authorization: Basic dXNlcjpwYXNz" "https://api.example.com/data"
}

generateJavaScript(String url, String username, String password, {String method = 'GET'})

Generates JavaScript fetch code with Basic Auth.

final result = FpdBasicAuthGenerator.generateJavaScript(
  'https://api.example.com/data',
  'user',
  'pass',
);
if (result.isSuccess) {
  print(result.data);
  // fetch('https://api.example.com/data', {
  //   method: 'GET',
  //   headers: {
  //     'Authorization': 'Basic dXNlcjpwYXNz'
  //   }
  // })
  // .then(response => response.json())
  // .then(data => console.log(data))
  // .catch(error => console.error('Error:', error));
}

πŸ”§ Data Types

BasicAuthHeader

Contains all information about a Basic Auth header.

class BasicAuthHeader {
  final String header;           // Full header: "Authorization: Basic ..."
  final String base64Credentials; // Base64 part only
  final String username;         // Extracted username
  final String password;         // Extracted password
}

Result<T>

Generic result wrapper for success/failure handling.

class Result<T> {
  final T? data;           // Success data (null on failure)
  final String? error;     // Error message (null on success)
  bool get isSuccess;      // true if successful
  bool get isFailure;      // true if failed
}

πŸ’‘ Examples

Basic Usage

import 'package:fpd_basic_auth_generator/fpd_basic_auth_generator.dart';

void main() {
  // Generate header
  final result = FpdBasicAuthGenerator.generateHeader('admin', 'secret123');
  if (result.isSuccess) {
    print('Header: ${result.data!.header}');
    // Output: Header: Authorization: Basic YWRtaW46c2VjcmV0MTIz
  }
}

Decoding Headers

void decodeExample() {
  final header = 'Authorization: Basic dXNlcjpwYXNz';
  final result = FpdBasicAuthGenerator.decodeHeader(header);
  
  if (result.isSuccess) {
    print('Username: ${result.data!.username}'); // user
    print('Password: ${result.data!.password}'); // pass
  } else {
    print('Error: ${result.error}');
  }
}

Validation

void validationExample() {
  final headers = [
    'Authorization: Basic dXNlcjpwYXNz',
    'Invalid: Header',
    'Authorization: Bearer token',
  ];
  
  for (final header in headers) {
    final isValid = FpdBasicAuthGenerator.isValidHeader(header);
    print('$header: ${isValid ? "Valid" : "Invalid"}');
  }
}

Command Generation

void commandExample() {
  // Generate cURL command
  final curlResult = FpdBasicAuthGenerator.generateCurl(
    'https://api.example.com/users',
    'admin',
    'secret123',
    method: 'GET',
  );
  
  if (curlResult.isSuccess) {
    print('cURL: ${curlResult.data}');
  }
  
  // Generate JavaScript code
  final jsResult = FpdBasicAuthGenerator.generateJavaScript(
    'https://api.example.com/users',
    'admin',
    'secret123',
  );
  
  if (jsResult.isSuccess) {
    print('JavaScript: ${jsResult.data}');
  }
}

Error Handling

void errorHandlingExample() {
  // Empty username
  final result1 = FpdBasicAuthGenerator.generateHeader('', 'pass');
  if (result1.isFailure) {
    print('Error 1: ${result1.error}'); // Username cannot be empty
  }
  
  // Invalid header format
  final result2 = FpdBasicAuthGenerator.decodeHeader('Invalid Header');
  if (result2.isFailure) {
    print('Error 2: ${result2.error}'); // Invalid header format
  }
  
  // Invalid Base64
  final result3 = FpdBasicAuthGenerator.decodeCredentials('invalid_base64!@#');
  if (result3.isFailure) {
    print('Error 3: ${result3.error}'); // Error decoding credentials
  }
}

Round-trip Conversion

void roundTripExample() {
  const username = 'testuser';
  const password = 'testpass123';
  
  // Generate header
  final headerResult = FpdBasicAuthGenerator.generateHeader(username, password);
  if (headerResult.isSuccess) {
    print('Generated: ${headerResult.data!.header}');
    
    // Decode header
    final decodeResult = FpdBasicAuthGenerator.decodeHeader(headerResult.data!.header);
    if (decodeResult.isSuccess) {
      print('Decoded username: ${decodeResult.data!.username}');
      print('Decoded password: ${decodeResult.data!.password}');
      
      // Verify round-trip
      final isCorrect = username == decodeResult.data!.username && 
                       password == decodeResult.data!.password;
      print('Round-trip successful: $isCorrect'); // true
    }
  }
}

πŸ”’ HTTP Basic Authentication

HTTP Basic Authentication is a simple authentication scheme that:

  1. Combines username and password in format username:password
  2. Encodes the combination in Base64
  3. Includes the result in header Authorization: Basic <credentials>

Example Flow:

Username: admin
Password: secret123
Combined: admin:secret123
Base64: YWRtaW46c2VjcmV0MTIz
Header: Authorization: Basic YWRtaW46c2VjcmV0MTIz

Use Cases:

  • REST APIs: Authenticate API requests
  • Web Services: Secure service communication
  • Application Authentication: Simple client-server auth
  • Testing: Validate authentication endpoints

πŸ§ͺ Testing

Run the tests:

dart test

Run with coverage:

dart test --coverage=coverage
genhtml coverage/lcov.info -o coverage/html

πŸ“‹ Requirements

  • Dart SDK: >=3.7.0 <4.0.0
  • Dependencies: meta: ^1.11.0

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Run the tests
  6. Submit a pull request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ”— Related Packages

πŸ“ž Support


Made with ❀️ by the FlutterPilot team

About

A Dart package for generating HTTP Basic Authentication headers from username and password

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages