generateAuthKey method

Future<String> generateAuthKey({
  1. required String apiKey,
  2. required String tailnetId,
})

Generates an auth key locally on the client. The generated auth key can then be used to connect to the given tailnet. This is done by the tailnet admin when connecting themselves to the tailnet, as well as for generating one-time invite links to invite others.

Implementation

Future<String> generateAuthKey({
  /// The admin API key used to perform authenticated API requests to the tailscale API.
  required String apiKey,

  /// The ID of the tailnet to generate an auth key for.
  required String tailnetId,
}) async {
  final override = generateAuthKeyOverride;
  if (override != null) {
    return override(apiKey: apiKey, tailnetId: tailnetId);
  }

  final url = Uri.parse('$_baseUrl/tailnet/$tailnetId/keys');
  final basicAuth = 'Basic ${base64Encode(utf8.encode('$apiKey:'))}';

  final response = await http.post(
    url,
    headers: {'Authorization': basicAuth, 'Content-Type': 'application/json'},
    body: jsonEncode({
      'capabilities': {
        'devices': {
          'create': {
            'reusable': false,
            'ephemeral': false,
            'preauthorized': true,
          },
        },
      },
      'expirySeconds': 86400,
    }),
  );

  if (response.statusCode == 200) {
    final json = jsonDecode(response.body);
    return json['key'] as String;
  }

  throw Exception(
    'Failed to generate key: ${response.statusCode} - ${response.body}',
  );
}