How to send Refresh Token for new Access Token to Microsoft Graph (Passport-Azure-AD OIDCStrategy)
I'm having trouble understanding how to send back a refresh token to get a new access token.
I've looked at this documentation: https://developer.microsoft.com/en-us/graph/docs/concepts/nodejs and I basically need help with Authenticate User- step4 but they don't seem to go into more details.
I tried using passport-oauth2-refresh but I think because I'm using Azure AD, I kept getting Error: Cannot register: not an OAuth2 strategy. So I've decided to try to manually check the expiry instead.
I am able to retrieve a refresh token (POST /token with req.user.refreshToken) along with my access token and I store it in json but I don't know how to send it back.
Here is my index.js:
const express = require('express');
const router = express.Router();
const graphHelper = require('../utils/graphHelper.js');
const passport = require('passport');
const request = require('request');
const SERVER = process.env.SERVER;
let user_id = null;
router.get('/', (req, res) =>
if (!req.isAuthenticated())
res.render('login');
else
renderBotPage(req, res);
);
router.get('/login',
passport.authenticate('azuread-openidconnect', failureRedirect: '/'),
(req, res) =>
res.redirect('/');
);
router.get('/token',
function (req, res, next)
passport.authenticate('azuread-openidconnect',
response: res, // required
failureRedirect: '/'
)
,
function (req, res)
const options =
headers:
'content-type' : 'application/json'
,
method: 'POST',
url: SERVER,
json:
'accessToken': req.user.accessToken,
'refreshToken': req.user.refreshToken
;
request(options,
function (error, response, body)
if (!error && response.statusCode === 200)
console.log(body)
);
console.log('We received a return from AzureAD get token.');
res.redirect('/');
);
router.post('/token',
function (req, res, next)
passport.authenticate('azuread-openidconnect',
response: res, // required
failureRedirect: '/'
)(req, res, next);
,
function (req, res)
console.log('res after first token function', res);
const options =
headers:
'content-type' : 'application/json'
,
method: 'POST',
url: SERVER,
json:
'accessToken': req.user.accessToken,
'refreshToken': req.user.refreshToken
;
request(options,
function (error, response, body)
if (!error && response.statusCode === 200)
console.log(body)
);
res.redirect('/');
);
function renderBotPage(req, res)
graphHelper.getUserData(req.user.accessToken, (err, user) =>
if (!err)
res.render('chatbotOn',
display_name: user.body.displayName,
user_id:user.body.id
);
else
// Catch of Expired token error
if (hasAccessTokenExpired(err))
req.session.destroy(() =>
req.logOut();
res.clearCookie('graphNodeCookie');
res.status(200);
res.redirect('/');
);
renderError(err, res);
res.render('chatbotOn',
display_name: "Random User"
);
);
router.get('/disconnect', (req, res) =>
req.session.destroy(() =>
req.logOut();
res.clearCookie('graphNodeCookie');
res.status(200);
res.redirect('/');
);
);
function hasAccessTokenExpired(e)
let expired;
if (!e.innerError)
expired = false;
else
expired = e.forbidden &&
e.message === 'InvalidAuthenticationToken' &&
e.response.error.message === "Le token d'accès a expiré.";
return expired;
function renderError(e, res)
e.innerError = (e.response) ? e.response.text : '';
res.render('error',
error: e
);
module.exports = router;
My app.js
const callback = (iss, sub, profile, accessToken, refreshToken, done) =>
done(null,
profile,
accessToken,
refreshToken
);
;
passport.use(new OIDCStrategy(config.creds, callback));
And here is my graphHelper.js:
const request = require('superagent');
function getUserData(accessToken, callback)
request
.get('https://graph.microsoft.com/beta/me')
.set('Authorization', 'Bearer ' + accessToken)
.end((err, res) =>
callback(err, res);
);
exports.getUserData = getUserData;
here is my config.js:
module.exports =
creds:
redirectUrl: 'http://localhost:3000/token',
clientID: 'xxxxx', // regular
clientSecret: 'xxxxx', // regular
identityMetadata:
'xxxxxx',
allowHttpForRedirectUrl: true, // For development only
responseType: 'code id_token',
validateIssuer: false, // For development only
responseMode: 'form_post',
scope: ['openid', 'offline_access', 'Contacts.Read',
'Calendars.ReadWrite'
]
,
;
node.js azure-active-directory passport.js microsoft-graph
add a comment |
I'm having trouble understanding how to send back a refresh token to get a new access token.
I've looked at this documentation: https://developer.microsoft.com/en-us/graph/docs/concepts/nodejs and I basically need help with Authenticate User- step4 but they don't seem to go into more details.
I tried using passport-oauth2-refresh but I think because I'm using Azure AD, I kept getting Error: Cannot register: not an OAuth2 strategy. So I've decided to try to manually check the expiry instead.
I am able to retrieve a refresh token (POST /token with req.user.refreshToken) along with my access token and I store it in json but I don't know how to send it back.
Here is my index.js:
const express = require('express');
const router = express.Router();
const graphHelper = require('../utils/graphHelper.js');
const passport = require('passport');
const request = require('request');
const SERVER = process.env.SERVER;
let user_id = null;
router.get('/', (req, res) =>
if (!req.isAuthenticated())
res.render('login');
else
renderBotPage(req, res);
);
router.get('/login',
passport.authenticate('azuread-openidconnect', failureRedirect: '/'),
(req, res) =>
res.redirect('/');
);
router.get('/token',
function (req, res, next)
passport.authenticate('azuread-openidconnect',
response: res, // required
failureRedirect: '/'
)
,
function (req, res)
const options =
headers:
'content-type' : 'application/json'
,
method: 'POST',
url: SERVER,
json:
'accessToken': req.user.accessToken,
'refreshToken': req.user.refreshToken
;
request(options,
function (error, response, body)
if (!error && response.statusCode === 200)
console.log(body)
);
console.log('We received a return from AzureAD get token.');
res.redirect('/');
);
router.post('/token',
function (req, res, next)
passport.authenticate('azuread-openidconnect',
response: res, // required
failureRedirect: '/'
)(req, res, next);
,
function (req, res)
console.log('res after first token function', res);
const options =
headers:
'content-type' : 'application/json'
,
method: 'POST',
url: SERVER,
json:
'accessToken': req.user.accessToken,
'refreshToken': req.user.refreshToken
;
request(options,
function (error, response, body)
if (!error && response.statusCode === 200)
console.log(body)
);
res.redirect('/');
);
function renderBotPage(req, res)
graphHelper.getUserData(req.user.accessToken, (err, user) =>
if (!err)
res.render('chatbotOn',
display_name: user.body.displayName,
user_id:user.body.id
);
else
// Catch of Expired token error
if (hasAccessTokenExpired(err))
req.session.destroy(() =>
req.logOut();
res.clearCookie('graphNodeCookie');
res.status(200);
res.redirect('/');
);
renderError(err, res);
res.render('chatbotOn',
display_name: "Random User"
);
);
router.get('/disconnect', (req, res) =>
req.session.destroy(() =>
req.logOut();
res.clearCookie('graphNodeCookie');
res.status(200);
res.redirect('/');
);
);
function hasAccessTokenExpired(e)
let expired;
if (!e.innerError)
expired = false;
else
expired = e.forbidden &&
e.message === 'InvalidAuthenticationToken' &&
e.response.error.message === "Le token d'accès a expiré.";
return expired;
function renderError(e, res)
e.innerError = (e.response) ? e.response.text : '';
res.render('error',
error: e
);
module.exports = router;
My app.js
const callback = (iss, sub, profile, accessToken, refreshToken, done) =>
done(null,
profile,
accessToken,
refreshToken
);
;
passport.use(new OIDCStrategy(config.creds, callback));
And here is my graphHelper.js:
const request = require('superagent');
function getUserData(accessToken, callback)
request
.get('https://graph.microsoft.com/beta/me')
.set('Authorization', 'Bearer ' + accessToken)
.end((err, res) =>
callback(err, res);
);
exports.getUserData = getUserData;
here is my config.js:
module.exports =
creds:
redirectUrl: 'http://localhost:3000/token',
clientID: 'xxxxx', // regular
clientSecret: 'xxxxx', // regular
identityMetadata:
'xxxxxx',
allowHttpForRedirectUrl: true, // For development only
responseType: 'code id_token',
validateIssuer: false, // For development only
responseMode: 'form_post',
scope: ['openid', 'offline_access', 'Contacts.Read',
'Calendars.ReadWrite'
]
,
;
node.js azure-active-directory passport.js microsoft-graph
add a comment |
I'm having trouble understanding how to send back a refresh token to get a new access token.
I've looked at this documentation: https://developer.microsoft.com/en-us/graph/docs/concepts/nodejs and I basically need help with Authenticate User- step4 but they don't seem to go into more details.
I tried using passport-oauth2-refresh but I think because I'm using Azure AD, I kept getting Error: Cannot register: not an OAuth2 strategy. So I've decided to try to manually check the expiry instead.
I am able to retrieve a refresh token (POST /token with req.user.refreshToken) along with my access token and I store it in json but I don't know how to send it back.
Here is my index.js:
const express = require('express');
const router = express.Router();
const graphHelper = require('../utils/graphHelper.js');
const passport = require('passport');
const request = require('request');
const SERVER = process.env.SERVER;
let user_id = null;
router.get('/', (req, res) =>
if (!req.isAuthenticated())
res.render('login');
else
renderBotPage(req, res);
);
router.get('/login',
passport.authenticate('azuread-openidconnect', failureRedirect: '/'),
(req, res) =>
res.redirect('/');
);
router.get('/token',
function (req, res, next)
passport.authenticate('azuread-openidconnect',
response: res, // required
failureRedirect: '/'
)
,
function (req, res)
const options =
headers:
'content-type' : 'application/json'
,
method: 'POST',
url: SERVER,
json:
'accessToken': req.user.accessToken,
'refreshToken': req.user.refreshToken
;
request(options,
function (error, response, body)
if (!error && response.statusCode === 200)
console.log(body)
);
console.log('We received a return from AzureAD get token.');
res.redirect('/');
);
router.post('/token',
function (req, res, next)
passport.authenticate('azuread-openidconnect',
response: res, // required
failureRedirect: '/'
)(req, res, next);
,
function (req, res)
console.log('res after first token function', res);
const options =
headers:
'content-type' : 'application/json'
,
method: 'POST',
url: SERVER,
json:
'accessToken': req.user.accessToken,
'refreshToken': req.user.refreshToken
;
request(options,
function (error, response, body)
if (!error && response.statusCode === 200)
console.log(body)
);
res.redirect('/');
);
function renderBotPage(req, res)
graphHelper.getUserData(req.user.accessToken, (err, user) =>
if (!err)
res.render('chatbotOn',
display_name: user.body.displayName,
user_id:user.body.id
);
else
// Catch of Expired token error
if (hasAccessTokenExpired(err))
req.session.destroy(() =>
req.logOut();
res.clearCookie('graphNodeCookie');
res.status(200);
res.redirect('/');
);
renderError(err, res);
res.render('chatbotOn',
display_name: "Random User"
);
);
router.get('/disconnect', (req, res) =>
req.session.destroy(() =>
req.logOut();
res.clearCookie('graphNodeCookie');
res.status(200);
res.redirect('/');
);
);
function hasAccessTokenExpired(e)
let expired;
if (!e.innerError)
expired = false;
else
expired = e.forbidden &&
e.message === 'InvalidAuthenticationToken' &&
e.response.error.message === "Le token d'accès a expiré.";
return expired;
function renderError(e, res)
e.innerError = (e.response) ? e.response.text : '';
res.render('error',
error: e
);
module.exports = router;
My app.js
const callback = (iss, sub, profile, accessToken, refreshToken, done) =>
done(null,
profile,
accessToken,
refreshToken
);
;
passport.use(new OIDCStrategy(config.creds, callback));
And here is my graphHelper.js:
const request = require('superagent');
function getUserData(accessToken, callback)
request
.get('https://graph.microsoft.com/beta/me')
.set('Authorization', 'Bearer ' + accessToken)
.end((err, res) =>
callback(err, res);
);
exports.getUserData = getUserData;
here is my config.js:
module.exports =
creds:
redirectUrl: 'http://localhost:3000/token',
clientID: 'xxxxx', // regular
clientSecret: 'xxxxx', // regular
identityMetadata:
'xxxxxx',
allowHttpForRedirectUrl: true, // For development only
responseType: 'code id_token',
validateIssuer: false, // For development only
responseMode: 'form_post',
scope: ['openid', 'offline_access', 'Contacts.Read',
'Calendars.ReadWrite'
]
,
;
node.js azure-active-directory passport.js microsoft-graph
I'm having trouble understanding how to send back a refresh token to get a new access token.
I've looked at this documentation: https://developer.microsoft.com/en-us/graph/docs/concepts/nodejs and I basically need help with Authenticate User- step4 but they don't seem to go into more details.
I tried using passport-oauth2-refresh but I think because I'm using Azure AD, I kept getting Error: Cannot register: not an OAuth2 strategy. So I've decided to try to manually check the expiry instead.
I am able to retrieve a refresh token (POST /token with req.user.refreshToken) along with my access token and I store it in json but I don't know how to send it back.
Here is my index.js:
const express = require('express');
const router = express.Router();
const graphHelper = require('../utils/graphHelper.js');
const passport = require('passport');
const request = require('request');
const SERVER = process.env.SERVER;
let user_id = null;
router.get('/', (req, res) =>
if (!req.isAuthenticated())
res.render('login');
else
renderBotPage(req, res);
);
router.get('/login',
passport.authenticate('azuread-openidconnect', failureRedirect: '/'),
(req, res) =>
res.redirect('/');
);
router.get('/token',
function (req, res, next)
passport.authenticate('azuread-openidconnect',
response: res, // required
failureRedirect: '/'
)
,
function (req, res)
const options =
headers:
'content-type' : 'application/json'
,
method: 'POST',
url: SERVER,
json:
'accessToken': req.user.accessToken,
'refreshToken': req.user.refreshToken
;
request(options,
function (error, response, body)
if (!error && response.statusCode === 200)
console.log(body)
);
console.log('We received a return from AzureAD get token.');
res.redirect('/');
);
router.post('/token',
function (req, res, next)
passport.authenticate('azuread-openidconnect',
response: res, // required
failureRedirect: '/'
)(req, res, next);
,
function (req, res)
console.log('res after first token function', res);
const options =
headers:
'content-type' : 'application/json'
,
method: 'POST',
url: SERVER,
json:
'accessToken': req.user.accessToken,
'refreshToken': req.user.refreshToken
;
request(options,
function (error, response, body)
if (!error && response.statusCode === 200)
console.log(body)
);
res.redirect('/');
);
function renderBotPage(req, res)
graphHelper.getUserData(req.user.accessToken, (err, user) =>
if (!err)
res.render('chatbotOn',
display_name: user.body.displayName,
user_id:user.body.id
);
else
// Catch of Expired token error
if (hasAccessTokenExpired(err))
req.session.destroy(() =>
req.logOut();
res.clearCookie('graphNodeCookie');
res.status(200);
res.redirect('/');
);
renderError(err, res);
res.render('chatbotOn',
display_name: "Random User"
);
);
router.get('/disconnect', (req, res) =>
req.session.destroy(() =>
req.logOut();
res.clearCookie('graphNodeCookie');
res.status(200);
res.redirect('/');
);
);
function hasAccessTokenExpired(e)
let expired;
if (!e.innerError)
expired = false;
else
expired = e.forbidden &&
e.message === 'InvalidAuthenticationToken' &&
e.response.error.message === "Le token d'accès a expiré.";
return expired;
function renderError(e, res)
e.innerError = (e.response) ? e.response.text : '';
res.render('error',
error: e
);
module.exports = router;
My app.js
const callback = (iss, sub, profile, accessToken, refreshToken, done) =>
done(null,
profile,
accessToken,
refreshToken
);
;
passport.use(new OIDCStrategy(config.creds, callback));
And here is my graphHelper.js:
const request = require('superagent');
function getUserData(accessToken, callback)
request
.get('https://graph.microsoft.com/beta/me')
.set('Authorization', 'Bearer ' + accessToken)
.end((err, res) =>
callback(err, res);
);
exports.getUserData = getUserData;
here is my config.js:
module.exports =
creds:
redirectUrl: 'http://localhost:3000/token',
clientID: 'xxxxx', // regular
clientSecret: 'xxxxx', // regular
identityMetadata:
'xxxxxx',
allowHttpForRedirectUrl: true, // For development only
responseType: 'code id_token',
validateIssuer: false, // For development only
responseMode: 'form_post',
scope: ['openid', 'offline_access', 'Contacts.Read',
'Calendars.ReadWrite'
]
,
;
node.js azure-active-directory passport.js microsoft-graph
node.js azure-active-directory passport.js microsoft-graph
edited Nov 15 '18 at 19:19
Linh Le Kim
asked Nov 14 '18 at 21:31
Linh Le KimLinh Le Kim
1517
1517
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53309029%2fhow-to-send-refresh-token-for-new-access-token-to-microsoft-graph-passport-azur%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53309029%2fhow-to-send-refresh-token-for-new-access-token-to-microsoft-graph-passport-azur%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown