首页 文章

nodejs oauth2令牌重生帮助需要

提问于
浏览
0

我在nodejs上做我的第一个测试应用程序 . 这很简单 . 从api获取数据并将其显示在浏览器上 . 以下是我遵循的步骤 .

  • 我使用express for web并请求获取api结果 .

  • 首先,我使用Oauth2客户端凭证方法从api服务器请求令牌 .

  • 我收到一个令牌并将其传递给资源网址并获取结果 .

  • 使用pug(Was Jade)teplate引擎将其显示在浏览器中 .

var express = require('express'); var tools = require('./ tools'); var app = express(); var request = require('request'); app.set('view engine','pug');

//获取令牌密钥tools.generateToken(function(response));

//索引页面路由app.get('/',function(req,res){// are.send('Hello World'令牌); 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(“示例应用程序监听http://%s:%s”,主机,端口)

})

一切似乎都很好 . 但是一旦令牌过期,我就无法检索任何结果(很明显) . 但我不知道何时获得新令牌 . 什么时候应该回忆起令牌生成功能?

还有一种方法可以在没有浏览器刷新的情况下跟踪api数据更改吗?请帮忙 . 谢谢

1 回答

  • 0

    您可以使用reqclient,它是 request 之上的小型客户端库,允许您自动处理OAuth2令牌刷新过程,因此如果OAuth2服务器在同一响应中为您提供到期时间, reqclient 将知道何时必须请求新的没有任何干预 .

    还有其他很好的功能,如cURL日志记录,以了解如何进行请求,Promise对象来处理响应,等等 . 它也可以安装 npm .

    这是一个如何创建 RequestClient 对象来处理针对API的请求的示例,还告诉模块谁是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
    

    这两个请求都将返回Promise对象,因此您必须处理 thencatch 如何处理它们 . 无论如何,因为使用 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":[]}
    

相关问题