【问题标题】:nodejs oauth2 token regeneration help needed需要nodejs oauth2令牌再生帮助
【发布时间】:2016-08-18 20:45:36
【问题描述】:

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

  1. 我使用 express for web 和 request 来获取 API 结果。
  2. 首先,我使用 Oauth2 客户端凭据方法从 API 服务器请求令牌。
  3. 我得到一个令牌并将它传递给资源 URL 并得到结果。
  4. 使用 pug (Was Jade) 模板引擎将其显示到浏览器。
    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 数据更改?请帮忙。谢谢。

【问题讨论】:

  • 任何提供对需要身份验证的资源的访问的路由都应该有一个身份验证中间件,您可以在此处检查令牌的有效性并在令牌合法时允许请求通过。通常,您会在此处更新 db/cache 中令牌的到期时间戳,以防止出现这种情况。

标签: node.js json api express oauth-2.0


【解决方案1】:

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

还具有其他不错的功能,例如 cURL 日志记录以了解请求是如何发出的,Promise 对象来处理响应等。它也可以与 @987654325 一起安装@。

这是一个如何创建 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":[]}

【讨论】:

    猜你喜欢
    • 2022-01-03
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    相关资源
    最近更新 更多