0

最近我在使用SAP云平台的机器学习API做和SAP系统的集成,因为SAP Cloud Platform Leonardo上的机器学期API,每次消费时需要传一个Access Token,故在每次实际调用API前,我需要先发一个请求去获取Access Token. 该请求的响应,除了返回实际的token外,还有一个过期时间,expires_in字段:

clipboard1,1

根据OAuth 2.0标准定义,expires_in字段代表服务器颁发的该token,距离过期时间还剩的秒数。

clipboard2,2

我的代码如下:

const request = require('request-promise-native');

var config = require('../config.js');
 
var TOKEN = undefined;
var EXPIRES_IN = undefined;
var TOKEN_FETCHED_SINCE = undefined;


function isCurrentDateExpired(){
    var current = new Date();

    var diffInMilliSeconds = current - TOKEN_FETCHED_SINCE;
    var diffInSecond = Math.ceil(diffInMilliSeconds/1000);
    var expired = diffInSecond >= EXPIRES_IN ? true:false;
    // for debug;
    // expired = true; 
    return expired;
}

async function getAccessToken(){
    if( TOKEN === undefined || isCurrentDateExpired()){
        var raw = new Buffer(config.username + ":" + config.password);
        const accessToken = await request({
            method: 'GET',
            headers: {
                'Authorization': 'Basic ' + raw.toString('base64')
            },
            url: config.ACCESS_TOKEN,
            json: false
        });
        var oToken = JSON.parse(accessToken);
        EXPIRES_IN = oToken.expires_in;
        TOKEN = oToken.access_token;
        TOKEN_FETCHED_SINCE = new Date();
        return oToken.access_token;
    }
    else{
        return TOKEN;
    }
}

var request1 = getAccessToken();
var freshNewToken, secondTimeToken;

request1.then(function(o){
    // console.log("token1: " + o);
     freshNewToken = o;
});

function test2(){
    var b = getAccessToken();
    b.then(function(o){
    // console.log("token2: " + o);
        secondTimeToken = o;
        console.log("they should be equal: " + (freshNewToken == secondTimeToken));
    });
}

setTimeout( test2, 6000);

要获取更多Jerry的原创文章,请关注公众号"汪子熙":
公众号截图


如果觉得我的文章对你有用,请随意赞赏

你可能感兴趣的

载入中...