401 unauthorized error in Flutter but works fine in Postman
Asked Answered
H

4

2

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

Please help.

Hazen answered 27/7, 2022 at 7:20 Comment(9)
You can check my answer here https://mcmap.net/q/375632/-flutter-dio-unauthorized-i-flutter-3668-401Libava
Typo at 'Authorization': '$token;',? There is : at the end of the $token.Libava
@MiftakhulArzak I am not using dio. I am using http.Hazen
You can use option 1 in my answer, make sure your rest api/server accept lower case header name.Libava
I haven't found a way for http libraryLibava
I don't have access to the backend. So option 1 is out of scope.Hazen
Just check if you are actually passing the correct token. Validate it in postman.Powell
Yes, It is working fine in Postman.Hazen
@SanjaySharma I can provide a repo link. Please help.Hazen
L
4

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
Libava answered 27/7, 2022 at 10:1 Comment(4)
No, it is not working.Hazen
Please help me. I am stuck for 2 daysHazen
@Arzak - Please accept my thanks for your response. I actually found it very helpful in resolving the problem.Emie
Tried, but not working for me, sadly.Bivouac
C
0

please pass token as

'Authorization': 'Bearer $token;',
Consonant answered 27/7, 2022 at 7:26 Comment(1)
I have already tried it. but not workingHazen
A
0
 _setAuthHeaders() => {
        'Accept': 'application/json',
        'Connection': 'keep-alive',
        'Authorization': 'Bearer $token',
      };
Abampere answered 27/7, 2022 at 8:34 Comment(2)
I have tried but not working. I have updated the question.Hazen
Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.Solar
G
0

If you are making flutter web project then please check at Inspect >> Console, that Refused to set unsafe header "content-length" is printing or not. If its happening then in your code where you have api setup

class ApiServiceProvider extends GetConnect {}
@override
  void onInit() {
    if (kIsWeb) {
      httpClient.addRequestModifier<void>((request) {
        request.headers.remove('user-agent');
        request.headers.remove('content-length');
        return request;
      });
    }
    super.onInit();
  }
Grimaldo answered 23/9, 2022 at 6:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.