httpflutterdartdigest-authentication

How to make Digest Authentication with http in Flutter?


I am trying to make an ApI request with Digest Authentication. I found an answer to the above question FLUTTER How to implement Digest Authentification but it is not very clear. The docs for digest are very minimal.

Following is my code

import 'package:http/io_client.dart' as io_client;
import 'package:http/http.dart' as http;

try {
  HttpClient authenticatingClient = HttpClient();

  authenticatingClient.authenticate = (uri, scheme, realm) {

    authenticatingClient.addCredentials(
        uri,
        realm,
        HttpClientDigestCredentials(
            DIGEST_AUTH_USERNAME, DIGEST_AUTH_PASSWORD));

    return Future.value(true);
  };

  http.Client client = io_client.IOClient(authenticatingClient);

  final response = await client.post(LOGIN_URL, body: {
    "username": userName,
    "password": password,
    "user_group": 2
  }).timeout(const Duration(seconds: 20));
  if (response.statusCode == 200) {

    debugPrint(response.body);
    CurvesLoginModel curvesLoginModel = standardSerializers.deserializeWith(
        CurvesLoginModel.serializer, json.decode(response.body));
    return curvesLoginModel;
  } else {
    return null;
  }
} on TimeoutException catch (_) {

  return null;
} on SocketException catch (_) {

  return null;
}


}

But what is realm in addCredentials.

Also is this the way to implement Digest Authentication in http for Flutter? As soon as I hit my endpoint I get the following error Unhandled Exception: type 'int' is not a subtype of type 'String' in type cast


Solution

  • Realm is an arbitrary string provided by the web server to help you decide which username to use, in case you have more than one. It's sort of analogous to domain. In one domain your username might be fbloggs, in another fredb. By telling you the realm/domain you know which to provide.

    Your cast problem is caused by using the value 2 in the body. That must be a Map<String, String>, but you have provided an integer. Replace it with 2.toString().