Search code examples
node.jsazureexpressoauth-2.0passport.js

Access to azure web-app using passport-azure-ad-oauth2


I am trying to authenticate my Azure Web App with passport-azure-ad-oauth2 in Node JS using express

I have tried to follow along with the documentation found here: https://github.com/auth0/passport-azure-ad-oauth2. I believe I have gotten the client ID, secret and callback URI correct...

When I go to localhost:3000, it redirects successfully to Office365 sign in. When I choose the pre-selected account, it just keeps looping back to the "select account"

When trying to sign in using an incognito window in Chrome it gives me the error: The reply URL specified in the request does not match the reply URLs configured for the application: '***appID'.

My code is obviously wrong and am hoping someone is able to possibly help me get it set up correctly.

Thanks in advance!!

My code is here

const express = require("express");
const bodyParser = require("body-parser")
const session = require('express-session');
const passport = require("passport");
const ejs = require("ejs");
const jwt = require("jwt-simple")


const AzureAdOAuth2Strategy = require('passport-azure-ad-oauth2').Strategy;


const app = express();

app.use(express.static("public"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(passport.initialize());
app.use(bodyParser.urlencoded({ extended: false }));



passport.use(new AzureAdOAuth2Strategy({
    clientID: 'azure client ID',
    clientSecret: 'secret',
    callbackURL: 'http://localhost:3000/auth/aad/callback',
    // resource: '00000002-0000-0000-c000-000000000000',
    // tenant: 'contoso.onmicrosoft.com'
  },
  function (accessToken, refresh_token, params, profile, done) {
    var waadProfile = profile || jwt.decode(params.id_token, '', true);
    console.log(waadProfile);
   
    User.findOrCreate({ id: waadProfile.upn }, function (err, user) {
      done(err, user);
    });
  }));


  app.get("/",passport.authenticate('azure_ad_oauth2'));

  app.get('/auth/aad/callback', 
  passport.authenticate('azure_ad_oauth2', { failureRedirect: '/login' }),
  function (req, res) {
    console.log(req);
    console.log(res);
    res.render('index');
  });



app.listen(process.env.PORT || 3000, function() {
    console.log("Server started on Port 3000");
  });

Solution

  • The callback URL in your code is not the same as the one set on Azure.

    That' why it says:

    The reply URL specified in the request does not match the reply URLs configured for the application: '***appID'.

    Set the correct URL on Azure to fix this.

    For the infinite redirection issue, clear the cache and cookie in your browser and it should work.

    However, if you don't correct the callback URL, it's going to happen again.