[英]nodejs oauth2 token regeneration help needed
我正在 nodejs 上做我的第一个测试应用程序。 这很简单。 从 api 获取数据并将其显示在浏览器上。 这是我遵循的步骤。
var express = require('express');
var tools = require('./tools');
var app = express();
var request = require('request');
app.set('view engine', 'pug');
// Get the token key
tools.generateToken(function(response){
token = response;
});
//Index Page routing
app.get('/', function (req, res) {
//res.send('Hello World '+token);
var request = require('request');
request('URL?access_token='+token+'&n=10&pgno=2', function (error, response, body) {
if (!error && response.statusCode == 200) {
res.render('index', { layout : 'layout', json: JSON.parse(body) });
}
})
});
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
一切似乎都运行良好。 但是一旦令牌过期,我将无法检索任何结果(很明显)。 但我不知道什么时候才能拿到新的令牌。 我什么时候应该召回令牌生成功能?
另外,有没有办法在不刷新浏览器的情况下跟踪 API 数据更改? 请帮忙。 谢谢。
您可以使用reqclient ,它是request
之上的一个小型客户端库,允许您自动处理 OAuth2 令牌刷新过程,因此如果 OAuth2 服务器在同一响应中为您提供到期时间, reqclient
将知道何时必须请求新的没有任何干预。
还有其他不错的功能,例如cURL日志记录以了解请求是如何发出的, Promise对象来处理响应等。它也可以与npm
一起安装。
这是一个如何创建RequestClient
对象来处理针对 API 的RequestClient
的示例,还告诉模块谁是 OAuth2 服务器,以及获取令牌的凭据是什么:
var client = new RequestClient({
baseUrl: "https://api.example.com/myapi"
,debugRequest:true, debugResponse:true // (optional) this activate curl logging
,oauth2: {
baseUrl: 'https://auth.example.com/oauth2'
,auth: {
user: 'client123' // The username, also called "client_id"
,pass: 'thePass123' // The password, also called "client_secret"
}
}
});
client.get("home-reports") // First will try to login with OAuth2, then /home-reports
.then(client.get("messages")); // Will reuse the previous token obtained if it's not expired yet, otherwise it will request a new one first
这两个请求将返回无极对象,所以你必须处理与then
和catch
与他们做什么。 无论如何,因为日志是用debugRequest:true, debugResponse:true
(可选)激活的,所有的请求和响应都将被记录在控制台中,如下所示:
[Requesting token]-> -X POST https://auth.example.com/oauth2/token -u ${CLIENT_ID}:${CLIENT_SECRET} -d 'grant_type=client_credentials'
[Response token]<- Status 200 - {"token_type":"bearer","access_token":"AAsdsAdggT5c0EkLng4yBEwght3bfDGf47hbSk3","expires_in":3456543}
[Requesting home-reports]-> https://api.example.com/myapi/home-reports -H "Authorization: Bearer ${ACCESS_TOKEN}"
[Response home-reports]<- Status 200 - {"sales":53434.53,"purchases":12984.04}
[Requesting messages]-> https://api.example.com/myapi/messages -H "Authorization: Bearer ${ACCESS_TOKEN}"
[Response messages]<- Status 200 - {"messages":[]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.