authenticate function

Future<MojangAccount> authenticate(
  1. String username,
  2. String password, {
  3. String? clientToken,
})

Authenticates a user with given credentials username and password. This only works with Mojang accounts and does not work with migrated Microsoft accounts.

clientToken should be identical for each request, otherwise old access tokens will be invalidated. If omitted, a randomly generated version 4 UUID will be used.

Implementation

Future<MojangAccount> authenticate(String username, String password,
    {String? clientToken}) async {
  final payload = {
    'agent': {'name': 'Minecraft', 'version ': 1},
    'username': username,
    'password': password,
    'clientToken': clientToken ?? Uuid().v4(),
    'requestUser': true
  };
  final response = await requestBody(
      http.post, _authServerApi, 'authenticate', payload,
      headers: {'content-type': 'application/json'});
  final data = parseResponseMap(response);
  if (data['error'] != null) {
    if (response.statusCode == 403) {
      throw AuthException(data['errorMessage']);
    } else if (response.statusCode == 400) {
      throw ArgumentError('Invalid username, password or client token.');
    } else if (data['error'] == 'GoneException') {
      // The account was migrated to a Microsoft account.
      throw Exception('The account has been migrated to a Microsoft account.');
    } else {
      throw Exception(data['errorMessage']);
    }
  }
  return MojangAccount.fromJson(data);
}