Home > front end >  Flutter REST api call with Basic auth returns 401, despite correct credentials
Flutter REST api call with Basic auth returns 401, despite correct credentials

Time:04-08

I'm trying to call an api from flutter but i keep getting 401 Unauthorized. According to the api documentation it uses basic authentiocation and is UTF-8 encoded. The username and password is provided by the docs and if try the api in a web browser and enter those credentials it goes through and i recieve the data. This is the code i'm using in flutter:

  Future<void> requestData() async {
    String username = 'abc';
    String password = '123';
    String basicAuth = 'Basic '   base64Encode(utf8.encode('$username:$password'));
    Response r = await get(
        Uri.parse('http://api.example.com'),
        headers: {
          HttpHeaders.authorizationHeader: basicAuth,
        });
    print(r.body);
    print(r.statusCode);
  }

I've also tried this variation which gave the same result:

headers: <String, String>{
  'authorization': basicAuth
}

Seeing as the username and password are correct there must be something wrong with how i make the call, but i've tried to do it a bunch of different ways and nothing works. Any help would be greatly appreciated!

CodePudding user response:

As per my experience, there is no need of token or basic auth while doing login. And login is post method not get.

CodePudding user response:

Turns out the documentation i read was outdated/incorrect. The api uses "Digest authentication" which i looked up and was able to implement. This is the code if anyone is interested:

import 'package:http/http.dart';
import 'package:http_auth/http_auth.dart';

...

Response res = await DigestAuthClient("USERNAME", "PASSWORD")
      .get(Uri.parse("API_URL")).timeout(const Duration(seconds: 20));
  • Related