Home > Software engineering >  Retrieve access token of an api call in Flutter
Retrieve access token of an api call in Flutter

Time:12-24

I have this below code which prints the access_token along with some other data when I print reponse.body. Printing reponse.headers["access_token] returns null and also printing response.body["access_token"] says The argument type 'String' can't be assigned to the parameter type 'int'.dart.

How would I be able to access just the access_token from the body?

final response = await http.post(
                            Uri.parse(
                                'https://login.microsoft.com/code/oauth2/token'),
                            headers: {
                              "Content-Type":
                                  "application/x-www-form-urlencoded",
                            },
                            body: {
                              "grant_type": "client_credentials",
                              //"grant_type": "authorization_code",
                              "client_id":
                                  "client-id",
                              "client_secret":
                                  "client secret",
                              "resource": "https://graph.microsoft.com"
                            },
                          );

                          if (response.statusCode == 200) {
                            print(response.body);

Here is response

{"token_type":"Bearer","expires_in":"3599","ext_expires_in":"3599","expires_on":"1671862627","not_before":"1671858727","resource":"https://graph.microsoft.com","access_token":"eyJ0eXAiOiJKV1QiLCJub25jZSI6InpoWUdxT0ItenRVeFFtM3dMcXZz

CodePudding user response:

Actually response.body is encoded json, so you can not access directly like this

response.body["access_token"]

you have to deocde the json and get your access token

Map<String, dynamic> body = jsonDecode(response.body);
print(body['access_token']);

CodePudding user response:

we should decode the json-encoded response.body inorder to access key's values from the body

try this

if (response.statusCode == 200) {
  var accessToken = json.decode(response.body)['access_token'];
}
  • Related