Azure AD for an Open Source based website – part 2 – node.js

Yesterday’s post showed you how you could take the “Writing your first Django app, part 1” tutorial and make it authenticate with Azure AD. This was deliberatly chosen since there is yet no Azure documentation for Python. However, there exists good examples for Java and Node.js on how to make a website use Azure AD as its authentication source. Just as an exercise, I ran through the steps just to show you the result so that you can see that there is not much difference between the Python-based and the Node.js-based solutions.

Building the sample

If you follow the sample “Web Sign-in and Sign-out with Azure AD” (see refs) you will get a working sample. There are a few npm install commands missing in the documentation so before you run it the first time you should issue the following commands

npm install cookie-parser
npm install express-session
npm install body-parser
npm install passport

I also added the support for EJS layout for which I had to install another package and add a few lines to the app.js file

npm install ejs-locals
var app = express()
var engine = require('ejs-locals');    <-- added

app.configure(function() {
  app.engine('ejs', engine);           <-- added
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.set('layout', 'myLayout');       <-- added
  app.use(express.logger());
  app.use(express.methodOverride());
  app.use(cookieParser());
  app.use(expressSession({ secret: 'keyboard cat', resave: true, saveUninitialized: false }));
  app.use(bodyParser.urlencoded({ extended : true }));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));  <-- changed
});

For some reason, the static path in the github sources points way off, so I had to change that line too.

In the comments of the article it is pointed out that the identityMetadata is wrong in the config.js. If you don’t fix that, the app will start but authentication will not be successful.

identityMetadata: 'https://login.microsoftonline.com/common/.well-known/openid-configuration',

The Result

The example will look less colorful if you run it straight of but the functionality will be the same. I added EJS layout support for my sample and used bootstrap CSS/javascript to pimp it up and make it look like my Django-based Python sample

aadnode-website-1

aadnode-website-2

aadnode-website-3

 

References

Azure AD documentation – Web Sign-in and Sign-out with Azure AD (Node.js)
https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-openidconnect-nodejs/