Home > Software design >  401 unauthorized error in Flutter but works fine in Postman
401 unauthorized error in Flutter but works fine in Postman

Time:07-28

I have Laravel endpoints. Login, Register and Home(where getData() will be working).

the register API and Login API is working fine but the problem is with the HomePage API where it will not ask for user details, it's a get method where it will return the details upon checking whether the user is logged-In or not.

  var token;

  _getKey() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    token = prefs.getString('key');
    print("this is Key $token");
  }
saveKey(String key) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('key', key);
  }
  getData() async {
    await _getCSRF();
    await _getKey();
    print(_setAuthHeaders());
    String uri = "$baseUrlUser/user_bal";
    try {
      return await http.get(Uri.parse(uri), headers: _setAuthHeaders());
    } catch (e) {
      return e;
    }
  }

  _setAuthHeaders() => {
        'Accept': 'application/json',
        'Connection': 'keep-alive',
        'Authorization': 'Bearer $token',
      };

A token is printing here: This is token

result of hitting the endpoint in the browser. This is the header which I want to access

CodePudding user response:

please pass token as

'Authorization': 'Bearer $token;',

CodePudding user response:

 _setAuthHeaders() => {
        'Accept': 'application/json',
        'Connection': 'keep-alive',
        'Authorization': 'Bearer $token',
      };

CodePudding user response:

http library automatically converts the header name to lower-case, may your server not accepting lower-case header name. Follow this step:

  1. Find io_client.dart in External Libraries->Dart Packages->http-x.xx->src->io_client.dart
  2. Find this code inside io_client.dart (line 40)
request.headers.forEach((name, value) {
  ioRequest.headers.set(name, value);
});
  1. Add preserveHeaderCase: true
request.headers.forEach((name, value) {
  ioRequest.headers.set(name, value,preserveHeaderCase:true);
});
  1. Clean your project and rebuild
  • Related