make sure created tokens don't live longer than the authorization

This commit is contained in:
tigerbot 2017-07-24 16:02:36 -06:00
parent 2dfbd235c9
commit ed0aca5783
2 changed files with 22 additions and 3 deletions

View File

@ -14,6 +14,7 @@
"bluebird": "^3.5.0",
"elliptic": "^6.4.0",
"jsonwebtoken": "^7.4.1",
"jwk-to-pem": "^1.2.6"
"jwk-to-pem": "^1.2.6",
"ms": "^2.0.0"
}
}

22
rest.js
View File

@ -8,6 +8,22 @@ function makeB64UrlSafe(b64) {
return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=*$/, '');
}
function timespan(duration, max) {
var timestamp = Math.floor(Date.now() / 1000);
if (typeof duration === 'string') {
duration = Math.floor(require('ms')(duration) / 1000);
}
if (typeof duration !== 'number') {
return timestamp;
}
if (max && timestamp+duration > max) {
return max - timestamp;
}
return duration;
}
module.exports.create = function (bigconf, deps, app) {
var Jwks = { restful: {} };
var Grants = { restful: {} };
@ -445,16 +461,18 @@ module.exports.create = function (bigconf, deps, app) {
kid: jwk.kid
}
};
var accessOpts = {expiresIn: timespan(req.body.exp || '1d', token_info.exp)};
var refreshOpts = {expiresIn: timespan(req.body.refresh_exp, token_info.exp)};
var jwt = require('jsonwebtoken');
var result = {};
result.scope = token_info.scope;
result.access_token = jwt.sign(payload, pem, Object.assign({expiresIn: req.body.exp || '1d'}, opts));
result.access_token = jwt.sign(payload, pem, Object.assign(accessOpts, opts));
if (req.body.refresh_token) {
if (token_info.refresh_token) {
result.refresh_token = token_info.refresh_token;
} else {
result.refresh_token = jwt.sign(payload, pem, Object.assign({expiresIn: req.body.refresh_exp}, opts));
result.refresh_token = jwt.sign(payload, pem, Object.assign(refreshOpts, opts));
}
}
return result;