0

I am using Laravel for my back end and Flutter for my front end.

When the token is stored, I use my local storage:

localStorage.setString('token',json.encode(body['access_token']));

This works fine. The token is stored as expected. But when I try to get it back from localStorage using:

token = localStorage.getString('token');

Then the token will be returned in the following format:

> \"eyJ0eXAiOiJKV1[...]a0\" where the backslash located in the start and finish of the token which were NOT supposed to be there.

How can I remove them before using it for a call on my backend?

However, before the store event, I use DebugPrint() to "see" that the token is returned from my call to Laravel. With debugPrint(), I get the proper result of the token which looks like : >"eyJ0eXAiOiJ[...]|"

I am using the method bellow to create a call to pass to my backend:

  getData(apiUrl) async {
    var fullUrl = _url + apiUrl;
    await getToken();

    return await http.get(Uri.parse(fullUrl), headers: _setHeaders());
  }

the part with Bearer is now stored BUT some additional characters are added to it. More specifically, " on the start and on the end of my token string.

 getData(apiUrl) async {
    var fullUrl = _url + apiUrl;
    token = await Network.getToken();

    // debugPrint(token);

    return await http.get(Uri.parse(fullUrl), headers: _setHeaders());
  }

  _setHeaders() => {
        'Content-type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer $token',
      };
}
Daco
  • 1
  • 2
  • do you want to remove leading backslash(\\) or third brack `[]` from your string? – Jahidul Islam Oct 18 '21 at 10:46
  • If I am right, your string token is being returned as encoded text, you might need to modify it via splitting – runtimeTerror Oct 18 '21 at 11:47
  • @JahidulIslam the bracket is to minimize the token size. No, what I want to do is to remove the backslashes that flutter included in the String of token once it stored the token. @runtimeTerror so that means that I have to somehow manipulate the String itself? If I try the same call from Postman or using a debugPrint() the token returns as expected : ``eyJ0eXAiOiJKV1QiLC[...]JRk6o`` – Daco Oct 18 '21 at 13:40

2 Answers2

0

But if you need to remove last and first elements on your String, try this,

String token = "\eyJ0\";
  List<String> list = token.split(""); // ['\', 'e', 'y', 'j', '0', '\']
  list.removeAt(0); // ['e', 'y', 'j', '0', '\']
  list.removeLast(); // ['e', 'y', 'j', '0']

final String backslashRemovedToken = list.join();
Anushka Pubudu
  • 389
  • 3
  • 10
  • thank you for the reply. However I don;t think that this is the proper solution. I think it has to do with how flutter handles the incoming string from Laravel and how it stores that incoming String. I find it weird that after the store – Daco Oct 18 '21 at 13:44
0

You can follow this for token store and retrieve it from local storage.

  static Future<SharedPreferences> getSharedPref() async {
    return await SharedPreferences.getInstance();
  }

  static saveToken(String token) async {
    await getSharedPref().then((SharedPreferences pref) {
      pref.setString("token", token);
      print("saving token $token");
    });
    getToken();
  }

  static Future<String> getToken() async {
    return await getSharedPref().then((SharedPreferences pref) {
      String token = pref.getString("token");
      // print("getting token $token");
      return token;
    });
  }

final accessToken = await PreferenceManager.getToken();

N.B: don't forget to use async and await

Jahidul Islam
  • 11,435
  • 3
  • 17
  • 38
  • thank your for your reply. I will try to see if it works. However, I think this is an encoding issue that I happening with SharedPreferences.getInstance() and localStorage when flutter stores my json.encode(token) – Daco Oct 18 '21 at 13:53
  • when you retrieve it just decode `token = jsonDecode(localStorage.getString('token'));` – Jahidul Islam Oct 18 '21 at 14:06
  • changed my code to: `String? token = jsonDecode(localStorage.getString('token').toString()); ` but got an error: `Error: Expected a value of type 'String?', but got one of type '_Future' ` – Daco Oct 18 '21 at 14:27
  • @Daco updated my answer have a look. – Jahidul Islam Oct 18 '21 at 14:53
  • I will. Regards – Daco Oct 19 '21 at 16:07
  • it looks like the problem persists. `token = \"eyJ0e[...MORE STRING DATA...]M\" but notice the start of my value: \" on the beginning and \" on the end! – Daco Oct 24 '21 at 18:27
  • you should check your response data. For myself, use this same method and it works – Jahidul Islam Oct 25 '21 at 05:36
  • please check my updated code in my question – Daco Oct 28 '21 at 14:15
  • can you explain what you exactly want? – Jahidul Islam Oct 29 '21 at 03:30
  • I want my application to store the incoming token to its localStorage. Then, retrieve that token and use it in my HTTP calls in order to validate that a user is actually registered (has logged in) and has a valid token. If the token is not valid, print a message that says unauthorized or something – Daco Nov 11 '21 at 11:51