检查 Oauth2 令牌在 Node.js Rest Client With Bluebird 中是否存在且有效

Check Oauth2 token exists and valid in Node.js Rest Client With Bluebird

我正在为使用 OAuth2 的 REST API 编写一个 Node.js 客户端。我正在使用 Bluebird 和 promises(并在 header 中发送访问令牌),我想知道什么时候是检查访问令牌是否已被授予(存在)或仍然有效(未过期)的好时机。

到目前为止,我想出了这个:

'use strict';

var Bluebird = require('bluebird');
var request = Bluebird.promisifyAll(require('request'), { multiArgs: true });
var Oauth = require('oauth');
var OAuth2 = OAuth.OAuth2;
var _ = require('lodash');

function Client(options) {

    this.options = _.assign({
        url: '<API URL>',
        oauth2Url: 'oauth2/token',
        apiVersion: process.env.apiVersion,
        consumerKey: process.env.consumerKey,
        consumerSecret: process.env.consumerSecret
    }, options);

    if (!this.options.url) {
        throw new Error('Missing client url.');
    }

    ...

    if (!this.options.consumerSecret) {
        throw new Error('Missing consumer secret.');
    }


    if(!this.access_token){
        var oauth2 = new OAuth2(
            this.options.consumerKey,
            this.options.consumerSecret,
            this.options.url + this.options.version,
      null,
            this.options.oauth2Url,
            null);
        oauth2.getOAuthAccessToken(
       '',
       {'grant_type':'client_credentials'},
       function (e, access_token, refresh_token, results){
                 this.access_token = access_token;
                 this.refresh_token = refresh_token;
       done();
     });
    }

}

Client.prototype.queryApi = function (options, callback) {
    return request.postAsync({
        headers: {
        Authorization: 'Bearer ' + access_token
    },
        url: this.options.url + this.options.apiVersion,
        body: JSON.stringify(options)}).
        then(function (result) {
            var json = JSON.parse(result[1]);

            if (_.isFunction(callback)) {
                callback(null, json);
            }
            return json;
        }).
        catch(function (err) {
            if (_.isFunction(callback)) {
                callback(err);
                return;
            }
            throw err;
        });
};

module.exports = Client;

我是 Oauth/Oauth2 和 Node.js 的新手,我只是想知道我是否在正确的位置检查访问令牌,how/where 我是否也可以检查它过期与否。谢谢!

首先有两种方法可以检查访问令牌是否过期

  • 通过了解来自您的 oauth app.In 的 token_expiration 值,在这种情况下,您需要在您的应用程序上保留任务 运行,以确定 access_token 是否过期。 (不推荐的处理访问令牌的方式)
  • 处理来自授权服务器的响应,指出您的访问令牌已 expired.In 在这种情况下,您需要通过出示刷新令牌来获取新的访问令牌。

您可以编写 'tokenPersistanceFunction',它会在您的 oauth 值(access_token、refresh_token)更新时被调用。

我已修改您的代码以反映这些更改

    function tokenPersistanceFunction(updatedOauth){

        // Here you will get Updated Oauth values 
        // Save these to DB
        return saveAccessToken(updatedOauth.access_token, updatedOauth.refresh_token);
    }

    Client.prototype.queryApi = function (options, tokenPersistanceFunction, callback) {
        return request.postAsync({
            headers: {
            Authorization: 'Bearer ' + access_token
        },
            url: this.options.url + this.options.apiVersion,
            body: JSON.stringify(options)}).
            then(function (result) {

                // You have some indication from your oauth server, that your access_token is expired.
                // You can check your response here to know whether access_token is expired or not.

                // If access_token is expired, Make request to refresh access token.
                // In your case 
                if(AccessTokenIsExpired){
                    // Function that will make request to refresh access_token by presenting refresh_token
                    return <functionThatRefreshesAccessToken>( refreshAccessTokenOptions,tokenPersistanceFunction)
                  .then(function(result){

                      //Extract access_token, refresh_token from response
                      // call 'tokenPersistanceFunction' to store these token in your DB.

                      return tokenPersistanceFunction(updatedOauth);

                  })
                  .then(function(savedOauthTokensSuccess){
                      // Now you have the updated Oauth tokens, you can make request to get resource
                      // this call will return you the actual response.
                      return queryApi(options, tokenPersistanceFunction, callback);
                  })
                }else{
                  var json = JSON.parse(result[1]);

                if (_.isFunction(callback)) {
                    callback(null, json);
                }
                return json;
                }


            }).
            catch(function (err) {
                if (_.isFunction(callback)) {
                    callback(err);
                    return;
                }
                throw err;
            });
    };