flutterpostmanaccess-token

How to get access token from API to use it in header of another API Auth 2.0


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

Solution

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