Bearer token request http flutter

56,534

Solution 1

token might not be set by the time it invokes http.get. Change it to

    String token = await Candidate().getToken();
    final response = await http.get(url, headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer $token',
    });
    print('Token : ${token}');
    print(response);

So that it is for sure set with right value.

Solution 2

Also you can use this method

String token = await Candidate().getToken();
final response = http.get(url,
        headers: {HttpHeaders.contentTypeHeader: "application/json", HttpHeaders.authorizationHeader: "Bearer $token"});

Solution 3

You just need to add the authorization field into the request header:

var token = await getToken();

http.post(
    "$url",
    headers: {
        "Content-Type": "application/json",
        'Authorization': 'Bearer $token',
    },
    encoding: Encoding.getByName("utf-8"),
).then((response) {
    if (response.statusCode == 200) {
        print(json.decode(response.body));
        // Do the rest of job here
    }
});

Solution 4

This is the other possible solution for the problem. You have to wait response of getToken() function before continuing. You can accomplish it in two different ways. Either use "then" or "await".

Future<List<Theme>> getThemes() async {
    String url = 'http://10.0.2.2:3000/v1/api/theme';
    String token;
    Candidate().getToken().then((value) {
        token = value;

        final response = await http.get(url, headers: {
           'Content-Type': 'application/json',
           'Accept': 'application/json',
           'Authorization': 'Bearer $token',
        });
        print('Token : ${token}');
        print(response);

        if (response.statusCode == 200) {
           List themesList = jsonDecode(response.body);
           List<Theme> themes = [];
           for (var themeMap in themesList) {
              themes.add(Theme.fromJson(themeMap));
           }
           return themes;
         } else {
             throw Exception('Failed to load themes');
         }
    });
}

Solution 5

This is a sample for a post request. You just need to add the header 'Authorization': 'Bearer $token'

final response = await http.post(
  url,
  headers: {'Authorization': 'Bearer $token'},
);
Share:
56,534

Related videos on Youtube

MayuriXx
Author by

MayuriXx

Updated on November 04, 2021

Comments

  • MayuriXx
    MayuriXx over 2 years

    I need to send my token for my API. I save my token in SharedPreferences and I can recupered this. My API need one, with the Bearer but how do ?

    I tested with Authorization, Http etc.

    Methods To save in SP

    Future<bool> setToken(String value) async {
        final SharedPreferences prefs = await SharedPreferences.getInstance();
        return prefs.setString('token', value);
      }
    
      Future<String> getToken() async {
        final SharedPreferences prefs = await SharedPreferences.getInstance();
        return prefs.getString('token');
      }
    
      Future<Candidate> candidateAuth({Map map}) async {
        String url = 'http://10.0.2.2:3000/v1/api/auth/candidate';
        await http
            .post(url,
                headers: {
                  'Content-type': 'application/json',
                  'Accept': 'application/json'
                },
                body: jsonEncode(map))
            .then((response) {
          if (response.statusCode == 201) {
            token = Candidate.fromJson(json.decode(response.body)).token;
            Candidate().setToken(token);
            return Candidate.fromJson(json.decode(response.body));
          } else {
            throw Exception('Failed auth');
          }
        });
      }
    }
    

    My API Call :

    
    Future<List<Theme>> getThemes() async {
        String url = 'http://10.0.2.2:3000/v1/api/theme';
        String token;
        Candidate().getToken().then((value) {
          token = value;
        });
        final response = await http.get(url, headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token',
        });
        print('Token : ${token}');
        print(response);
    
        if (response.statusCode == 200) {
          List themesList = jsonDecode(response.body);
          List<Theme> themes = [];
          for (var themeMap in themesList) {
            themes.add(Theme.fromJson(themeMap));
          }
          return themes;
        } else {
          throw Exception('Failed to load themes');
        }
      }
    
    

    My API return error 401 : unauthorized

    • Vivek Mishra
      Vivek Mishra over 4 years
      unauthorized means your token has expired and you need to fetch new token
    • MayuriXx
      MayuriXx over 4 years
      no when i enterred my token in my swagger is good @VivekMishra
  • Craig Howell
    Craig Howell almost 3 years
    Whenever I use this approach I end up with a blank version of Candidate instead of getting the original desired state. Anyone have a clue based on this little information what I am missing?
  • a.ak
    a.ak almost 3 years
    Add some description to explain your code.
  • Mathews  Musukuma
    Mathews Musukuma almost 2 years
    You have not put a description to explain your code, and also you are not doing the right thing. Where are you passing the authentication token?