Home > Net >  Flutter http can't get Bearer Token from .NET Api
Flutter http can't get Bearer Token from .NET Api

Time:05-23

I am starting flutter mobile development and have problem with http package http calls. I already have working API written in .NET with included Micorosft Identity. My goal is to create flutter mobile app that gets data from that API with authorizauion. I have problems implementing username-password authorization to get Token from API. Same API call works on Postman and in my existing Xamarin Forms App. Same problem with http call where in its header I use token which I get from Postman. Using VS Code, all packages installed, can retrive sample data from openweathermap.org in same flutter app. My code is:

  1. Recive Bearer Token from API:

     Future<String> authorization(String username, String password) async {
     Uri uri = Uri.parse('https://myapi/token');
     var request = http.MultipartRequest('POST', uri);
     request.fields.addAll({
       'grant_type': 'password',
       'username': username,
       'password': password,
     });
    
     http.StreamedResponse response = await request.send();
    
     if (response.statusCode == 200) {
       Map<String, dynamic> auth =
           jsonDecode(await response.stream.bytesToString());
    
       return auth['access_token'];
     } else {
       return "";
     }
    

    }

  2. GET Cars Data from API:

     Future<String> getCars() async {
     Uri uri = Uri.parse('https://myapi/api/getcars');
     var token =
         'WorkingToken';
     http.Response response = await http.get(uri, headers: {
       "Content-Type": "application/json; charset=UTF-8",
       "Authorization": "Bearer $token",
     });
    
     return response.body;
    

    }

CodePudding user response:

Microsoft Identity Authorization request expects application/x-www-form-urlencoded content.

Future<String> authorization(String username, String password) async {
  final response = await http.post(
    Uri.parse('https:/host/path/token'),
    headers: <String, String>{
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: <String, String>{
     'grant_type': 'password',
     'username': username,
     'password': password,
    },
    encoding: Encoding.getByName('utf-8')
  );

  if (response.statusCode == 200) {
    return jsonDecode(response.body)['access_token'];
  } else {
    throw Exception(response.reasonPhrase);
  }
}

CodePudding user response:

Your question is very general and your problem depends on your response data. Of course, I did not realize that you have a problem receiving the token or using the token as a header for another api! But since you are just starting to use Flutter, I suggest you to use the Chopper Library to work with HTTP services and api. It's very simple and fase.

  • Related