passport-azure-ad Single Sign On (SSO)

3.2k Views Asked by At

I am trying to set up authentication thru Azure AD for my website built with React, NodeJS, and Express using the passport-azure-ad package. Authentication works successfully and I am able to authenticate and retrieve a token, but the login prompt appears when logging in even if I have a logged in session on admin.microsoft.com or sharepoint.mytenant.com. I know the passport-azure-ad documentation says it is possible to use single-sign-on, but I have not been able to find any guidance on how to set it up.

passport strategy:

passport.use(new OIDCStrategy(
  {
    identityMetadata: `${process.env.OAUTH_ID_METADATA}`,
    clientID: process.env.OAUTH_APP_ID,
    responseType: 'code id_token',
    responseMode: 'form_post',
    redirectUrl: process.env.OAUTH_REDIRECT_URI,
    allowHttpForRedirectUrl: true,
    clientSecret: process.env.OAUTH_APP_PASSWORD,
    passReqToCallback: false,
    scope: process.env.OAUTH_SCOPES.split(' ')
  },
  signInComplete
));

signInComplete: users are currently stored in memory rather than a db. Uses simple-oath2.

async function signInComplete(iss, sub, profile, accessToken, refreshToken, params, done) {
  if (!profile.oid) {
    return done(new Error("No OID found in user profile."));
  }

  try{
    console.log('in here');
    const user = await graph.getUserDetails(accessToken);

    if (user) {
      // Add properties to profile
      profile['email'] = user.mail ? user.mail : user.userPrincipalName;
    }
  } catch (err) {
    return done(err);
  }

  // Create a simple-oauth2 token from raw tokens
  let oauthToken = oauth2.accessToken.create(params);

  // Save the profile and tokens in user storage
  users[profile.oid] = { profile, oauthToken };
  return done(null, users[profile.oid]);
}

Authorization functions:

/* GET auth callback. */
router.get('/signin',
  function  (req, res, next) {
    passport.authenticate('azuread-openidconnect', 
      {
        response: res,
        prompt: 'login',
        failureRedirect: '/',
        successRedirect: '/'
      }
    )(req,res,next);
  }
);

// <CallbackRouteSnippet>
router.post('/callback',
  function(req, res, next) {
    passport.authenticate('azuread-openidconnect',
      {
        response: res,
        failureRedirect: '/',
        successRedirect: '/'
      }
    )(req,res,next);
  }
);
// </CallbackRouteSnippet>

router.get('/signout',
  function(req, res) {
    req.session.destroy(function(err) {
      req.logout();
      res.redirect('/');
    });
  }
);

Any help is appreciated, thanks.

1

There are 1 best solutions below

1
On

Please refer to this sample it may help you https://github.com/AzureAD/passport-azure-ad

The sample passport-azure-ad has been tested to work with both Microsoft Azure Active Directory and with Microsoft Active Directory Federation Services.