I use Express to proxy requests to a separate API server that is protected by OAuth 2 access tokens. When the token expires, the server will return 401, which I am currently processing in my router middleware to switch and update the access token associated with the client session ( I am using express-session ).
Here is my code:
router.js
app.use('/api', require('./routes.js'));
routes.js
var express = require('express'), router = express.Router(), routesController = require('./routes.controller.js'); router.route('/*') .get(routesController.fetch);
routes.controller.js
module.exports.fetch = function(req, res, next) { var options = helpers.buildAPIRequestOptions(req); request(options, function(err, response, body){ if(response.statusCode === 401) { authController.refreshToken(req, res, next); } else { res.status(response.statusCode).send(body); } }); };
authController
module.exports.refreshToken = function(req, res, next) { var formData = { grant_type: 'refresh_token', refresh_token: req.session.refreshToken, scope: 'PRODUCTION' }, headers = { 'Authorization' : 'Basic ' + consts.CLIENT_KEY_SECRET_BASE64_DEV }; request.post({url:consts.ACCESS_TOKEN_REQUEST_URL_DEV, form:formData, headers: headers, rejectUnauthorized: false}, function(err, response, body){ var responseBody = JSON.parse(body); if (response.statusCode === 200) { req.session.accessToken = responseBody.access_token; req.session.refreshToken = responseBody.refresh_token; next();
After updating the token, I would like to resend the original API request, which I launch using the request module in my fetch controller.
I am a little puzzled by how I really do this, is there an elegant way to achieve this?
mindparse
source share