Loopback.io rest - how to get through the oAuth token

Using loopback, I created a connection to an existing API using a REST connector, which works well. I would like, however, to go through the oAuth token coming from the client.

I can get the oAuth token by capturing ctx.req.headers.authorizationfrom a method Model.beforeRemote, but I can’t figure out how to pass it to the REST connector as a new header.

I tried a couple of things:

  • Adding a hook with Model.observe(but this is not like starting a REST connector).
  • Using a template with an authorization field - but did not get the correct operation.

Any ideas appreciated.

+4
source share
2 answers

OAuth ( ). - ?

{
  connector: 'rest',
  debug: false,
  options: {
    "headers": {
      "accept": "application/json",
      "content-type": "application/json",
      "authorization": "{oauth}"
    },
    strictSSL: false,
  },
  operations: [
    {
      template: {
        "method": "GET",
        "url": "http://maps.googleapis.com/maps/api/geocode/{format=json}",
        "query": {
          "address": "{street},{city},{zipcode}",
          "sensor": "{sensor=false}"
        },
        "options": {
          "strictSSL": true,
          "useQuerystring": true
        },
        "responsePath": "$.results[0].geometry.location"
      },
      functions: {
        "geocode": ["oauth", "street", "city", "zipcode"]
      }
    }
  ]}
+1

. -, datasources.json REST-:

{
    "name": "connect",
    "connector": "rest",
    "debug": "true",
    "operations": [
      {
        "template": {
          "method": "GET",
          "url": "http://server/api",
          "headers":{
            "authorization": "Bearer {token}"
          }
        },
        "functions": {
          "get": ["token"]
        }
      }
    ]
  }

, auth .

-, , , API , , . :

module.exports = function (Model) {
  Model.disableRemoteMethod('invoke', true);
  Model.disableRemoteMethod('get', true);

  Model.call = function (req, cb) {
    var token = req.token;
    Model.get(token, function (err, result) {
      cb(null, result);
    });
  };
  Model.remoteMethod(
    'call',
    {
      http: {path: '/', verb: 'get'},
      accepts: [
        {arg: 'req', type: 'object', http: {source: 'req'}}
      ],
      returns: {
        root: true
      }
    }
  );
};

, req . , get invoke ( ).

, . . server.js:

app.use('/api', function (req, res, next) {
  oidc.authenticate(req, function (err, token) {
    if (err) {
      return res.send({status: 401, message: err});
    }
    req.token = token;
    next();
  });
});

OIDC , , , -.

0

Source: https://habr.com/ru/post/1584932/


All Articles