sharon
sharon

Reputation: 403

How to solve error 401 is not authorized in a Flutter app

This is the state when logging in to the homepage:

Future<User?> login(String nim, String password) async {
    String token = await UtilSharedPreferences.getToken();
    SharedPreferences pref = await SharedPreferences.getInstance();
    try {
      var body = {
        'username': nim,
        'password': password,
      };
      var response = await http.post(
        Uri.parse('http://dev.api.app.masoemuniversity.ac.id/v1/login_mhs'),
        headers: {
          'Authorization': 'Bearer $token',
        },
        body: body,
      );
      print(response.statusCode);
      print(response.body);
      if (response.statusCode == 200) {
        return User.fromJson(jsonDecode(response.body));
      } else {
        return null;
      }
    } catch (e) {
      print(e);
      return null;
    }
  }

And this is when I call user data after login

Future<User> getDataMahasiswa() async {
  String _token = await UtilSharedPreferences.getToken();
  SharedPreferences _pref = await SharedPreferences.getInstance();
  final response = await http.get(
    Uri.parse(
        'http://dev.api.app.masoemuniversity.ac.id/v1/auth/mhs_siakad/biodata'),
    headers: {
      'Authorization': 'Bearer $_token',
      "Content-Type": 'application/json'
    },
  );
  print(response.statusCode);
  print(response.body);
  if (response.statusCode == 200) {
    return User.fromJson(jsonDecode(response.body)['data']);
  } else {
    throw Exception();
  }
}

And this is the response when logging in with code 200 is successful, but when getting user data the response is code 401

I/flutter (15446): 200
I/flutter (15446): {"status":"success","data":{"nim":"20265028","name":"Sukandar","id_role":"f4d4d365-dc99-4fe7-b2b7-5daddf77e127","role":"Mahasiswa","level":7,"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiYzZlNGE3ZmFmZTAzZDYyODdhMDM2NTg4MjNiZmE0MDZjOGI4YWQ1OGQ5MTRjZDkzMzRkYjhmZDQzYjc3MjRmYWFiZDgwY2FiNzYzZjI0YTEiLCJpYXQiOjE2NjU2NDY5MzkuNzc4NTUsIm5iZiI6MTY2NTY0NjkzOS43Nzg1NTQsImV4cCI6MTY5NzE4MjkzOS43Njg5MzQsInN1YiI6ImM4MzljNmNlLTUxZDEtNGZmYS05MmIxLWQwM2FlZTQ5MWNmMSIsInNjb3BlcyI6W119.mfag9cVCgIyojIkPuXXi7-xfnAsbWds5DYRLgSovE6u6NtAI8s3ZMYVQ0X7Bgu6IE_DfNDNSB2lap6_fvv_lx41NCSvegPLcOa57XBy9dIcQOeg-rWo8B0kYnvsG2q_g4UFCx2FEnhVeWKuhyqDfM3kkG2IB3c1rGNkx50A9_uGeofqrTkxlnuTnkRnYjcTuGOEj6laRnkWsE9_HTfu2Q7-Te66ZYqIllc4CH4OaxBwSKgd3qMPrvy8sFenah6mx7RgZ2h9cpiFmTM-bj8WP6lc-DiqSJyvde14vebBNylg6NJKX7dpV7oeRJGlVDuMK4Dqihy4wDNAx4q_vCYQticiRrUwvhuXY9AZnD6IhXbqrwb0bYZE3f6eg1voKltpBiVxx0YSQkIGze_w9ceEDpZsFHWszJ0U7O99mL763kEjnZ4MM60Xyn9YZ5iRCT2uswWtljI0rUrGBgR1QPWJ5oMEOXR4CWfSZ8m7LrPwBGB_JCo8Y9Dyn6fDM-A6YSfrbXW1BlEd7eW6I
I/flutter (15446): 401
I/flutter (15446): Unauthorized.

Upvotes: 1

Views: 1984

Answers (1)

pmatatias
pmatatias

Reputation: 4434

idk the mechanism auth in your app. may be you can try this.

  • after success login you got this:
I/flutter (15446): 200
I/flutter (15446): {"status":"success","data":
{"nim":"20265028","name":"Sukandar","id_role":"f4d4d365-dc99-4fe7-b2b7-
5daddf77e127","role":"Mahasiswa","level":7,"access_token":"eyJ0eXAiO.....

see, now you have an access_token. use it for get the data from server

...
final response = await http.get(
   // do not use  UtilSharedPreferences.getToken();
   // because this token use for login, its require username and password in body
    Uri.parse(
    'http://dev.api.app.masoemuniversity.ac.id/v1/auth/mhs_siakad/biodata'),
    headers: {
      'Authorization': 'Bearer $access_token', 
      "Content-Type": 'application/json'
    },
  );
....

Upvotes: 3

Related Questions