Integrate Azure AD to Node.JS

auth.js

var passport = require(‘passport’);
var OIDCBearerStrategy = require(‘passport-azure-ad’).BearerStrategy;
var config = require(‘./config’);

var options = {
identityMetadata: config.creds.identityMetadata,
clientID: config.creds.clientID,
validateIssuer: config.creds.validateIssuer,
issuer: config.creds.issuer,
passReqToCallback: config.creds.passReqToCallback,
isB2C: config.creds.isB2C,
policyName: config.creds.policyName,
allowMultiAudiencesInToken: config.creds.allowMultiAudiencesInToken,
audience: config.creds.audience,
loggingLevel: config.creds.loggingLevel,
loggingNoPII: config.creds.loggingNoPII,
clockSkew: config.creds.clockSkew,
scope: config.creds.scope
};

var bearerStrategy = new OIDCBearerStrategy(options,
function (token, done) {
console.log(token);
if (!token.oid)
done(new Error(‘oid is not found in token’));
else {
owner = token.oid;
done(null, token);
}
}
);

passport.use(bearerStrategy);

module.exports = passport;

Config.js file

// Don’t commit this file to your public repos. This config is for first-run
exports.creds = {
// Requried
identityMetadata: ‘https://login.microsoftonline.com/{YOUR_TENANT_ID}/.well-known/openid-configuration',

// Required
clientID: ‘{YOUR_CLIENT_ID}’,

// Required.
// If you are using the common endpoint, you should either set `validateIssuer` to false, or provide a value for `issuer`.
validateIssuer: false,

// Required.
// Set to true if you use `function(req, token, done)` as the verify callback.
// Set to false if you use `function(req, token)` as the verify callback.
passReqToCallback: false,

// Required if you are using common endpoint and setting `validateIssuer` to true.
// For tenant-specific endpoint, this field is optional, we will use the issuer from the metadata by default.
issuer: “https://login.microsoftonline.com/{YOUR_TENANT_ID}/v2.0",

// Optional, default value is clientID
//audience: null,

// Optional. Default value is false.
// Set to true if you accept access_token whose `aud` claim contains multiple values.
allowMultiAudiencesInToken: false,

// Optional. ‘error’, ‘warn’ or ‘info’
loggingLevel:’info’,
};

index.js

app.use(passport.initialize()); // Starts passport

app.use(passport.session()); // Provides session support

app.use(bodyParser.urlencoded({ extended: true }));

app.use(bodyParser.json());

var router = require(‘./routes’)();

app.use(passport.authenticate(‘oauth-bearer’, {

session: false

}));

--

--