Search code examples
node.jsopenid-connectadalazure-ad-b2cpassport-azure-ad

Utilizing state/customState with passport-azure-ad


I'm having trouble figuring out the purpose of customState and if/how I can utilize it to pass data to the return url. Specifically I wish to route the user back to their original location after being signed in. I thought I could pass the original url to the parameter customState and have it returned back to me in the return url POST, but it appears to be encoded or perhaps replaced with a different value.

Here is what I want to achieve:

  1. Anonymous user visits /page/protected which requires authentication.
  2. Code calls passport.authenticate which in turn redirects the user to sign in.
  3. User signs in and is returned to the pre-configured return url e.g.: /auth/oidc/return.
  4. Code handles extracting information from form-post data.
  5. User is directed back to /page/protected.

Solution

  • A return URL (e.g. "/page/protected") can be round-tripped by:

    1) Setting the "customState" parameter before the authentication middleware redirects to Azure AD B2C:

    app.get('/login', function (req, res, next) {
      passport.authenticate('azuread-openidconnect', {
        response: res,
        resourceURL: config.resourceURL,
        customState: '/page/protected', // Or set to the current URL
        failureRedirect: '/'
      })(req, res, next);
    }, function (req, res) {
      res.redirect('/');
    });
    

    2) Getting the req.body.state parameter after the authentication middleware validates the authentication response from Azure AD B2C:

    app.post('/auth/openid/return', function (req, res, next) {
      passport.authenticate('azuread-openidconnect', {
        response: res,
        failureRedirect: '/'
      })(req, res, next);
    }, function (req, res) {
      res.redirect(req.body.state);
    });
    

    The "customState" parameter value should be encrypted, which will mean the req.body.state parameter will have to be decrypted, if you don't want the return URL to be tampered with.

    Otherwise, it is common to write the return URL to req.session before the authentication middleware redirects and sends the authentication request to Azure AD B2C, and then read (and then delete) this return URL from req.session after the authentication middleware receives and validates the authentication response from Azure AD B2C.