loopback.io rest连接器-如何通过oAuth令牌



使用环回,我已经使用REST连接器创建了一个到现有API的连接,该连接运行良好。然而,我想传递来自客户端的oAuth令牌。

我可以通过从Model.beforeRemote方法获取ctx.req.headers.authorization来获取oAuth令牌,但似乎无法找到将其作为新头传递给REST连接器的方法。

我试过几种方法:

  1. 使用Model.observe添加挂钩(但REST连接器似乎不会触发)
  2. 使用一个带有授权字段的模板,但无法使其正常工作

任何想法都值得赞赏。

使用下面的连接器,您应该能够将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"]
}
}
]}

想回答这个问题,并以Bryan的评论为基础。首先,在datasources.json中,您需要设置REST连接器:

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

正如Bryan所介绍的,可以将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方法(用更友好的REST资源替换它)。

最后,您需要将令牌放入请求中。为此,使用一些中间件就足够简单了。以下是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提供程序来验证令牌,但当然,您可以使用任何东西。

最新更新