Digital Assistant and Mobile

Get Involved. Join the Conversation.

Topic

    Abhishek Singh
    Failing to create connector to call CX Cloud REST api in MCS
    Topic posted August 30, 2018 by Abhishek SinghRed Ribbon: 250+ Points, tagged Bots, Mobile, OMCE 
    145 Views, 8 Comments
    Title:
    Failing to create connector to call CX Cloud REST api in MCS
    Content:

    Hi ,

    I have to call cx cloud rest api having uri path  /ccadmin/v1/products , this api needs access_token which we get by calling /ccadmin/v1/login. I have tried creating connector for the products api but failing in it. I have tested other connector like openweathermap and other publicly available rest api where i am successful.

    Through cURL or node code i am able to call these apis, but i am looking for connector thing so that instead of writing node code in my custom component, i can simply call the connector in custom component.

    Here is the cURL thing

    curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Authorization: Bearer app_secret_key" -d "grant_type=client_credentials" https://xyzyyyy.com/ccadmin/v1/login

      it returns access_token, pass this access_token to next api call

    curl -X GET -H "Authorization: Bearer access_token" https://xyzyyyy.com/ccadmin/v1/products

    My try:

    I have tried creating two connector one for each, but for /login i could not succeed, I had put all parameter in header. For /products it works well when i supply access_token manually to connector header parameter. But how can i create connector so that it fetches access_token from /login by itself

    Code Snippet:

    Comment

     

    • Frank Nimphius

      The code you are posting is no MCS code but generic Node Express code.  The access to the remote service is through Node Request module, not Oracle MCS. 

       

      For invoking connectors from Node code executing as a custom API in MCS, see: https://docs.oracle.com/en/cloud/paas/mobile-cloud/mcsua/calling-apis-custom-code.html#GUID-26DC731F-7C65-4209-95B2-4A9979CFF164

       

      Search for and read about "externalAuthorization"

      Here is a code snippet that reads the external authorization token from a request header attribute called 'external-authorization'. Note that this is where you would put the bearer token to 

       function (req, res) {
          req.oracleMobile.connectors.idmsamples.get(
            'repos/' + req.params.owner + '/' + req.params.repo + '/contents/' + req.params.path,
            {externalAuthorization: req.header('external-authorization')}, 
            {qs: {"branch": req.query.branch}, headers: {"accept": req.header('accept')}}
             ).then(
              function (result) {
                res.status(result.statusCode).send(result.result);
              },
              function (error) {
                res.status(error.statusCode).send(error.error);
              }
            );    
      });
      

       

      Note that this is how it works in MCS. Right now your code does not work in MCS as it seems

       

      Frank

       

       

       

    • Abhishek Singh

      Complete code is as below: it is working fine, i am getting JSON response out of it.

      /**
       * The ExpressJS namespace.
       * @external ExpressApplicationObject
       * @see {@link http://expressjs.com/3x/api.html#app}
       */
       
      /**
       * Mobile Cloud custom code service entry point.
       * @param {external:ExpressApplicationObject}
       * service
       */
      var request=require('request');
       
      module.exports = function(service) {
       
      var appkey = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1NmQ1MTU4OC05YjQwLTQxMWMtYjA3ZC1lMGI4YjBjODg2NGEiLCJpc3MiOiJhcHBsaWNhdGlvbkF1dGgiLCJleHAiOjE1NjI4MzcwMTUsImlhdCI6MTUzMTMwMTAxNX0';
      var tokenuri = 'https://ccadmin-stage-z2xa.oracleoutsourcing.com/ccadmin/v1/login';
      var serviceuri = 'https://ccadmin-stage-z2xa.oracleoutsourcing.com/ccadmin/v1/products';
       
       
      service.post('/mobile/custom/tst_cxproducts/products', function(req,res) {
       
        request({
          method: 'POST',
          uri: tokenuri,
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Bearer '+appkey,
          },
          form: {
            'grant_type': 'client_credentials'
          }
        }, function(err, value) {
          if (err) {
            console.log(err);
            res.status(500).json({ error: 'Cannot get access token' });
            return;
          }
          var json = JSON.parse(value.body);
          var accessToken = json.access_token;
          //console.log("Got Access Token:", accessToken);
          request({
            uri: serviceuri,
            headers: {
              'Authorization': 'Bearer '+accessToken,
            }
          }, function(err, value) {
             if (err) {
               console.log(err);
               res.status(503).json({ error: 'Cannot invoke service' });
               return;
             }
      // var jsonResponse=JSON.parse(value.body);
      // res.send(200,jsonResponse);
             res.status(200).json(value.body);
          });
        });
      });
       
      };
       
      I gone through the docs, still i am not clear how exactly my values need to be put there, like
       
      for ccadmin/v1/login api
       headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Bearer '+appkey,
          },
          form: {
            'grant_type': 'client_credentials'
          }
       
      and for for ccadmin/v1/products api
       
            headers: {
              'Authorization': 'Bearer '+accessToken,
            }
       
      NOt sure how exactly it would look like if we replace the below code with mine.
       
       {externalAuthorization: req.header('external-authorization')}, 
            {qs: {"branch": req.query.branch}, headers: {"accept": req.header('accept')}}
      
       
    • Abhishek Singh

      I tried with this code but it thrown error

       

        service.post('/mobile/custom/tst_cxproducts/products', function(req,res) {
       
      req.oracleMobile.connectors.cxproductsconnector.post('/',
          {externalAuthorization: req.header('external-authorization')},
          {qs: {}, headers: {"accept": req.header('accept'),
           'Content-Type': 'application/x-www-form-urlencoded',
                             'Authorization': 'Bearer '+appkey,
                             'grant_type': 'client_credentials'
                            }
          }
           ).then(
      function (result) {
                // include the target service's response headers
               
      res.set(result.headers);
      res.status(result.statusCode).send(result.result);
      },
      function (error) {
               
      res.status(error.statusCode).send(error.error);
      }
      );
       
        });
    • Frank Nimphius

       

      I assume its not authenticating ? Try and add the "Bearer " prefix to the token 

       

      Frank

    • Abhishek Singh

      Tried two approached, failed in both

      1.

          req.oracleMobile.connectors.cxproductsconnector.post(   
      '/login', // resource
               { externalAuthorization: req.header('external-authorization')},
              
           { qs: {},
           headers: { "accept": req.header('accept'),
           "Content-Type": req.header('application/x-www-form-urlencoded'),
                             "Authorization": req.header('Bearer '+appkey),
                            "grant_type": req.header('client_credentials')
                           }
           }

       

      2.

        var appkey = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eytYjA3ZCc3MiOiJhcHBsaWNhdGlvbkF1dGgiLCJleHAiOjE1NjI4MzcwMTUsImlhdCI6MTUzMTMwMTAxNX0=.Qh4nwp51z824xCxEj9A0gSkwM2Xf1T2+/8j3QG1hWLw=';
       
        var headers= {
                        'Content-Type': 'application/x-www-form-urlencoded',
                          'Authorization': 'Bearer '+appkey,
                      };
       
      var body = {
                    'grant_type' : 'client_credentials'
                    };
        service.post('/mobile/custom/tst_cxproducts/products', function(req,res) {
       
          req.oracleMobile.connectors.cxproductsconnector.post(
            '/login',
             body,
             {inType: 'json', externalAuthorization: 'Bearer '+appkey },
           {qs : {}, headers: headers}
    • Frank Nimphius

      Hi,

      the call "/login appears" to be wrong as it only should be the name of the resource to call. 

      According to the documentation, the externalAuthorization does not need to go to the header but the options, which is the second argument, only. This then is added to the header.

       

      Frank

       

       

    • Abhishek Singh

      Hi frank,

      I tried with lot of permutations and combinations as exactly i could not figure it out. here are some tried approach yet failed

          req.oracleMobile.connectors.cxproductsconnector.post(
      //    req.oracleMobile.connectors.cxproductsconnector.post(
      // 'login',
      // { externalAuthorization: 'Bearer '+appkey },
      //    {qs : {}, headers: headers}
       
       
      //post(resourceName, object, options, httpOptions)
       
         'login', // resource
      //    req.body, // object
      null,
      //   {  externalAuthorization: req.header('external-authorization')},  // options
        {  externalAuthorization: req.header('external-authorization') , inType: 'json'},  // options
                      //     null
       
              {  qs:     {}, 
               headers: { "accept": req.header('accept'),
                         "Content-Type": req.header('application/x-www-form-urlencoded'),
      "Authorization": req.header('Bearer '+appkey),
      "grant_type": req.header('client_credentials')
      }
                  }
      ).then(
    • Frank Nimphius

      There is not much I can do at the moment. You would need someone to work on your sample to explore what is going wrong for you. Not sure if this can be handled by customer support in a service request

      Frank