11
votes

Flutter http de la demande de jeton du porteur

Je dois envoyer mon jeton pour mon API. Je sauvegarde mon jeton dans SharedPreferences et je peux le récupérer. Mon API en a besoin, avec le Bearer mais comment faire?

J'ai testé avec Autorisation, Http etc.

Méthodes pour enregistrer dans SP

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');
    }
  }

Mon appel API:

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');
      }
    });
  }
}

Mon erreur de retour d'API 401: non autorisée


2 commentaires

non autorisé signifie que votre jeton a expiré et que vous devez récupérer un nouveau jeton


non quand j'ai entré mon jeton dans mon swagger c'est bien @VivekMishra


5 Réponses :


20
votes

token peut ne pas être défini au moment où il appelle http.get . Changez-le en

    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);

Pour qu'il soit bien sûr réglé avec la bonne valeur.


0 commentaires

1
votes

Le problème est que vous attribuez votre token d'une manière différente.

Lorsque vous faites cela, await asyncFunction(); Dart attendra qu'il soit terminé. Mais, lorsque vous aimez cette fonction asyncFunction().then((value) => print) cela indique à Dart qu'il peut continuer à exécuter votre code, et lorsque cette fonction asyncFunction est terminée, imprimez la valeur.

C'est ce qui se passe sur votre cas avec

Candidate().getToken().then((value) {
      token = value;
    });

Voici un exemple, exécutez-le sur Dart Pad.

Future.dart


0 commentaires

6
votes

Vous pouvez également utiliser cette méthode

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


0 commentaires

0
votes

Il vous suffit d'ajouter le champ d'autorisation dans l'en-tête de la demande:

getProfile() async {
print(getToken());
var token = await getToken();
http.post(
      "$url",
      headers: {
        "Content-Type": "application/json",
        'Authorization': 'Bearer $token',
      },
      encoding: Encoding.getByName("utf-8"),
    ).then((response) {
      print(datafromurl);
      if (response.statusCode == 200) {
         print(json.decode(response.body));
      }
    });
}


0 commentaires

0
votes

Ceci est un exemple pour une demande de publication. Il vous suffit d'ajouter l'en-tête 'Authorization': 'Bearer $ token'

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


0 commentaires