ZetCode

Dart HttpClientBasicCredentials

last modified October 18, 2026

The HttpClientBasicCredentials class in Dart provides a way to handle HTTP basic authentication. It's used with Dart's HttpClient for secure requests.

This class creates credentials for the Basic authentication scheme. It encodes username and password in base64 format for HTTP Authorization headers.

Basic Definition

HttpClientBasicCredentials is part of Dart's dart:io library. It implements credentials for HTTP basic authentication.

The class takes username and password parameters. It automatically handles the base64 encoding required by the Basic authentication scheme.

Basic Authentication Example

This example shows basic usage of HttpClientBasicCredentials.

main.dart
import 'dart:io';

void main() async {
  var client = HttpClient();
  var url = Uri.parse('https://httpbin.org/basic-auth/user/pass123');
  
  try {
    var credentials = HttpClientBasicCredentials('user', 'pass123');
    client.addCredentials(url, '', credentials);
    
    var request = await client.getUrl(url);
    var response = await request.close();
    await response.drain<void>();
    print('Response status: ${response.statusCode}');
  } finally {
    client.close();
  }
}

We create an HttpClient and register basic credentials with client.addCredentials. The client adds the proper Authorization header to requests for that URL automatically.

$ dart main.dart
Response status: 200

Handling Authentication Errors

This example demonstrates error handling with basic authentication.

main.dart
import 'dart:io';

void main() async {
  var client = HttpClient();
  var url = Uri.parse('https://httpbin.org/basic-auth/user/pass123');
  
  try {
    var credentials = HttpClientBasicCredentials('wrong', 'credentials');
    client.addCredentials(url, '', credentials);
    
    var request = await client.getUrl(url);
    var response = await request.close();
    await response.drain<void>();
    
    if (response.statusCode == HttpStatus.unauthorized) {
      print('Authentication failed');
    } else {
      print('Response status: ${response.statusCode}');
    }
  } finally {
    client.close();
  }
}

We check for 401 Unauthorized status code when credentials are invalid. The example shows proper error handling for authentication failures.

$ dart main.dart
Authentication failed

Using with HttpClientRequest

This example shows how credentials registered on the client apply to a request created with HttpClientRequest.

main.dart
import 'dart:io';

void main() async {
  var client = HttpClient();
  var url = Uri.parse('https://httpbin.org/post');
  
  try {
    var credentials = HttpClientBasicCredentials('admin', 'secret');
    client.addCredentials(url, '', credentials);
    
    var request = await client.postUrl(url);
    request.write('{"data": "value"}');
    var response = await request.close();
    await response.drain<void>();
    
    print('Response status: ${response.statusCode}');
  } finally {
    client.close();
  }
}

Credentials belong to HttpClient, not HttpClientRequest. We register them with client.addCredentials before opening the request; the client then adds the Authorization header when the request is sent.

$ dart main.dart
Response status: 200

Multiple Authentication Attempts

This example shows handling multiple authentication attempts.

main.dart
import 'dart:io';

void main() async {
  var attempts = [
    ('user1', 'pass1'),
    ('user2', 'pass2')
  ];
  var url = Uri.parse('https://httpbin.org/basic-auth/user2/pass2');
  
  for (var (username, password) in attempts) {
    var client = HttpClient();
    
    try {
      var credentials = HttpClientBasicCredentials(username, password);
      client.addCredentials(url, '', credentials);
      
      var request = await client.getUrl(url);
      var response = await request.close();
      await response.drain<void>();
      if (response.statusCode == HttpStatus.ok) {
        print('Authenticated as $username');
        break;
      } else {
        print('Failed with $username: ${response.statusCode}');
      }
    } catch (e) {
      print('Failed with $username: $e');
    } finally {
      client.close();
    }
  }
}

We try multiple credential pairs until successful authentication. Invalid credentials produce a 401 response, so we inspect the status code. A fresh client is used for each attempt so the previous credentials are not reused. This pattern is useful when working with multiple possible accounts.

$ dart main.dart
Failed with user1: 401
Authenticated as user2

Secure Credential Handling

This example demonstrates secure credential management practices.

main.dart
import 'dart:io';

class SecureAuth {
  final String _username;
  final String _password;
  
  SecureAuth(this._username, this._password);
  
  HttpClientBasicCredentials get credentials {
    return HttpClientBasicCredentials(_username, _password);
  }
}

void main() async {
  var auth = SecureAuth('secureUser', 'secret');
  var client = HttpClient();
  var url = Uri.parse('https://httpbin.org/basic-auth/secureUser/secret');
  
  try {
    client.addCredentials(url, '', auth.credentials);
    
    var request = await client.getUrl(url);
    var response = await request.close();
    await response.drain<void>();
    print('Response status: ${response.statusCode}');
  } finally {
    client.close();
  }
}

We encapsulate credentials in a secure class to prevent accidental exposure. This pattern helps maintain security when working with authentication.

$ dart main.dart
Response status: 200

Best Practices

Source

Dart HttpClientBasicCredentials Documentation

This tutorial covered Dart's HttpClientBasicCredentials class with practical examples showing authentication patterns and security considerations.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Dart tutorials.