ZetCode

Dart HttpClientCredentials

last modified October 18, 2026

The HttpClientCredentials class in Dart provides authentication credentials for HTTP requests. It's used with HttpClient for secure communication.

HttpClientCredentials handles basic authentication, digest authentication, and other credential types. It's part of Dart's dart:io library.

Basic Definition

HttpClientCredentials is an abstract interface class representing HTTP auth credentials. Concrete implementations include Basic, Bearer, and Digest credentials.

The concrete classes store the credentials and know which authentication scheme to use. They work with HttpClient's authentication API for secure requests.

Basic Authentication

This example shows basic HTTP authentication using HttpClientCredentials.

main.dart
import 'dart:io';

void main() async {
  var client = HttpClient();
  
  // Set up credentials
  var credentials = HttpClientBasicCredentials('user', 'pass123');
  
  var url = Uri.parse('https://httpbin.org/basic-auth/user/pass123');
  
  // Add credentials for the URL
  client.addCredentials(
    url,
    '',
    credentials
  );
  
  try {
    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 basic credentials and associate them with a specific URL. The HttpClient sends these credentials automatically for requests that match the registered URL prefix.

$ dart main.dart
Response status: 200

Digest Authentication

This example demonstrates digest authentication with HttpClientCredentials.

main.dart
import 'dart:io';

void main() async {
  var client = HttpClient();
  
  // Set up digest credentials
  var credentials = HttpClientDigestCredentials('admin', 'secret');
  var url = Uri.parse('https://httpbin.org/digest-auth/auth/admin/secret');
  
  client.addCredentials(
    url,
    'me@kennethreitz.com',
    credentials
  );
  
  try {
    var request = await client.getUrl(url);
    var response = await request.close();
    await response.drain<void>();
    print('Admin access granted: ${response.statusCode}');
  } finally {
    client.close();
  }
}

Digest authentication is more secure than basic auth. The credentials are hashed before transmission. The server must support digest authentication, and the realm passed to addCredentials must match the server's realm.

$ dart main.dart
Admin access granted: 200

Multiple Credentials

This example shows using different credentials for different URL paths.

main.dart
import 'dart:io';

void main() async {
  var client = HttpClient();
  
  // User credentials for user area
  client.addCredentials(
    Uri.parse('https://httpbin.org/basic-auth/john/doe123'),
    '',
    HttpClientBasicCredentials('john', 'doe123')
  );
  
  // Admin credentials for admin area
  client.addCredentials(
    Uri.parse('https://httpbin.org/basic-auth/admin/master'),
    '',
    HttpClientBasicCredentials('admin', 'master')
  );
  
  try {
    // Access user area
    var userRequest = await client.getUrl(
      Uri.parse('https://httpbin.org/basic-auth/john/doe123')
    );
    var userResponse = await userRequest.close();
    await userResponse.drain<void>();
    print('User status: ${userResponse.statusCode}');
    
    // Access admin area
    var adminRequest = await client.getUrl(
      Uri.parse('https://httpbin.org/basic-auth/admin/master')
    );
    var adminResponse = await adminRequest.close();
    await adminResponse.drain<void>();
    print('Admin status: ${adminResponse.statusCode}');
  } finally {
    client.close();
  }
}

We register different credentials for different URL paths. HttpClient selects the credentials whose registered URL is the longest matching prefix of the request URL.

$ dart main.dart
User status: 200
Admin status: 200

Handling Authentication Errors

This example demonstrates error handling for failed authentication.

main.dart
import 'dart:io';

void main() async {
  var client = HttpClient();
  
  var url = Uri.parse('https://httpbin.org/basic-auth/user/pass123');
  
  client.addCredentials(
    url,
    '',
    HttpClientBasicCredentials('wrong', 'credentials')
  );
  
  try {
    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('Success: ${response.statusCode}');
    }
  } on SocketException catch (e) {
    print('Network error: $e');
  } finally {
    client.close();
  }
}

When authentication fails, the server returns 401 Unauthorized. We check the status code to handle authentication failures gracefully.

$ dart main.dart
Authentication failed

Custom Authentication Scheme

Dart only supports the Basic, Bearer, and Digest credential types. To customize how credentials are selected, use the authenticate callback. It is invoked when the server issues an authentication challenge and can register credentials before the request is retried.

main.dart
import 'dart:io';

void main() async {
  var client = HttpClient();
  var url = Uri.parse('https://httpbin.org/basic-auth/user/pass123');
  
  client.authenticate = (url, scheme, realm) async {
    print('Authenticating to $url with $scheme (realm: $realm)');
    client.addCredentials(
      url,
      realm ?? '',
      HttpClientBasicCredentials('user', 'pass123')
    );
    return true;
  };
  
  try {
    var request = await client.getUrl(url);
    var response = await request.close();
    await response.drain<void>();
    print('API response: ${response.statusCode}');
  } finally {
    client.close();
  }
}

The authenticate callback provides custom logic for handling authentication challenges. Here it registers basic credentials when the server asks for them.

$ dart main.dart
Authenticating to https://httpbin.org/basic-auth/user/pass123 with Basic (realm: Fake Realm)
API response: 200

Best Practices

Source

Dart HttpClientCredentials Documentation

This tutorial covered Dart's HttpClientCredentials class with practical examples showing basic and digest authentication, error handling, and custom schemes.

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.