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
Bearer tokens enable requests to authenticate using an access key, such as a JSON Web Token (JWT). The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list. In the Token field, enter your API key value.
Generating Tokens You can generate tokens on the server by creating a Server Client and then using the Create Token method. If generating a token to use client side, the token must include the userID claim in the token payload, where as server tokens do not.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With