Home > Enterprise >  flutter: How to get access token from api to use it in header of another api Auth 2.0
flutter: How to get access token from api to use it in header of another api Auth 2.0

Time:08-18

I am working on an app where i have an api to get access token and then i want to use that access token in header of another api to get authenticated. Auth 2.0 is used... i get the access token and access api in postman but i don't know how to do it in flutter. please help

here is the code

     Future getToken() async {
        final uri = Uri.parse("https://.....");
        var requestBody = {
            "client_id": "clientid",
          "client_secret": "clientpassword",
          "redirect_uri": uri,
          "grant_type": "client_credentials"
        };
      
var response = await http.post(
          uri,
          body: json.encode(requestBody),
        );
    
        print(response.body);
      }

CodePudding user response:

as I assumed that you are trying to send access token in header of each api request for an example you can see below code you can store token in a variable from response and use that variable

     Future getToken() async {
        final uri = Uri.parse("https://.....");
        var requestBody = {
            "client_id": "clientid",
          "client_secret": "clientpassword",
          "redirect_uri": uri,
          "grant_type": "client_credentials"
        };
      
var response = await http.post(
          uri,
          body: json.encode(requestBody),headers: {
      'Content-Type': 'application/json; charset=UTF-8',
      'Authorization': 'Bearer $Token'
    };
        ),
    
        print(response.body);
      }
  • Related