↓ Skip to main content
A picture painted behind glass: a closed teal double gate in a pale wall. Beside it stands a small gatehouse with a teal roof and a closed shutter. One orange visitor badge hangs on a hook at the gatehouse.

Logging In Through MAS: OIDC Against coreidp

Our skeleton of a companion app asks nobody for a password. It sends the browser to the identity provider of the suite, which IBM calls coreidp, and gets a token back. This page follows that flow through our skeleton and shows the place where it broke when we changed one setting.

MAS 9.2 series companion app sign-in

The app is the skeleton of From Skeleton to a Running App, deployed on our test system on the MAS 9.2 series, under path routing. The requests on this page are ours.

The flow
#

d2 diagram d2 diagram

An authorization code flow. Step 6 is the only one that the browser never sees.

What the first answer holds
#

We asked the app for its page with no session. It answered 302, and the address in the answer was the authorize address of the suite with these parts:

PartValue
response_typecode
client_idthe name of the app
redirect_urithe app’s address, with /auth/callback under its base path
scopeopenid profile email general
code_challenge_methodS256, with a code challenge
statea state value

The same answer set one cookie of the app, the session. Its path is the base path of the app, and it is HttpOnly, Secure and SameSite=Lax.

Under path routing the cookie has a name of the app’s own. All apps of the suite share one host there. The default name of the session library could collide with the session of another app, so our deployment sets the name to the name of the app.

The code
#

This is the whole sign-in module of the skeleton:

/**
 * Sign-in with OIDC (authorization code) against coreidp, the identity provider of the suite.
 *
 * A passport-oauth2 strategy pointed at coreidp. Client id and secret are read from the
 * mounted secret of the sign-in client. The access token is kept in the server-side
 * session. The app is a confidential web client (client_secret_basic), the client that
 * the registration Job creates.
 */
import { type Express, type Request, type Response, type NextFunction, Router } from "express";
import passport from "passport";
import { Strategy as OAuth2Strategy } from "passport-oauth2";
import { jwtDecode } from "jwt-decode";
import { config } from "../config.js";
import { getMountedSecret } from "../secrets.js";

interface SessionUser {
  accessToken: string;
  refreshToken?: string;
}

// Every redirect carries the base path: under path routing the app lives at <domain>/<base>.
const callbackUrl = (req: Request) => `https://${req.get("host")}${config.basePath}/auth/callback`;
const home = () => `${config.basePath}/`;

export function setupOpenIDAuth(app: Express): void {
  const clientID = config.isProduction
    ? getMountedSecret(config.oauthClientMount, "oauth-client-id", "CLIENT_ID")
    : "mockedClientId";
  const clientSecret = config.isProduction
    ? getMountedSecret(config.oauthClientMount, "oauth-client-secret", "CLIENT_SECRET")
    : "mockedClientSecret";

  // Dev fallbacks let the strategy construct without a cluster; the flow is never
  // exercised in dev (checkAuthentication short-circuits when !isProduction).
  const oidcUri = config.oidcUri || "https://localhost/oidc/endpoint/MaximoAppSuite";
  const tokenUrl = config.tokenUrl || "https://localhost/oidc/endpoint/MaximoAppSuite/token";

  const strategy = new OAuth2Strategy(
    {
      authorizationURL: `${oidcUri}/authorize`,
      tokenURL: tokenUrl,
      clientID,
      clientSecret,
      passReqToCallback: true,
      skipUserProfile: true,
      pkce: true,
      state: true,
    },
    // verify: we only care about the tokens; the JWT carries identity.
    (_req: Request, accessToken: string, refreshToken: string, _params: unknown, _profile: unknown, done: (e: unknown, u?: SessionUser) => void) => {
      done(null, { accessToken, refreshToken });
    },
  );

  passport.use(strategy);
  passport.serializeUser((u, done) => done(null, u as SessionUser));
  passport.deserializeUser((u, done) => done(null, u as SessionUser));
  app.use(passport.initialize());
  app.use(passport.session());
}

/** Gate that ensures a valid, unexpired MAS session; redirects to coreidp otherwise. */
export const checkAuthentication = (req: Request, res: Response, next: NextFunction): void => {
  const token = (req.session as any)["x-access-token"] ?? (req.user as SessionUser | undefined)?.accessToken;

  const login = () => {
    (req.session as any).returnTo = req.originalUrl;
    passport.authenticate("oauth2", {
      scope: config.scopes.split(" "),
      callbackURL: callbackUrl(req),
      successReturnToOrRedirect: home(),
    } as any)(req, res, next);
  };

  // Expired token -> log out and restart the flow.
  if (req.isAuthenticated() && config.isProduction && token) {
    const { exp } = jwtDecode<{ exp: number }>(token);
    if (exp < Math.floor(Date.now() / 1000)) return req.logOut(() => login());
  }

  if (req.isAuthenticated() || !config.isProduction) {
    // The access token stays in the server-side session. It is never sent to the browser.
    if (!(req.session as any)["x-access-token"] && token) (req.session as any)["x-access-token"] = token;
    return next();
  }
  return login();
};

export const OpenIDRoutes = Router();

OpenIDRoutes.get("/login", (req, res, next) =>
  passport.authenticate("oauth2", {
    scope: config.scopes.split(" "),
    callbackURL: callbackUrl(req),
    successReturnToOrRedirect: home(),
  } as any)(req, res, next),
);

OpenIDRoutes.get("/auth/callback", (req, res, next) =>
  passport.authenticate("oauth2", {
    callbackURL: callbackUrl(req),
    successReturnToOrRedirect: (req.session as any)?.returnTo ?? home(),
    failureRedirect: `${config.basePath}/failure`,
  } as any)(req, res, next),
);

OpenIDRoutes.get("/failure", (_req, res) => res.status(401).send("Authentication failed"));

OpenIDRoutes.get("/logmeout", (req, res) => {
  req.logout(() => {
    req.session.destroy(() => {
      const exit = `?logoutExitPage=${encodeURIComponent(`${config.authApiUri}/endpage`)}`;
      res.redirect(`${config.logoutUri}${exit}`);
    });
  });
});

The strategy is the one of the open-source library passport-oauth2, with PKCE and state switched on. The verify function keeps two things, the access token and the refresh token.

The token stays on the server. The access token lives in the session of the app, in the memory of the pod. The browser gets only the session cookie. The app’s own address api/whoami returns the user and the issuer, and it leaves the token out.

For every request the gate reads the expiry from the token. With an expired token, checkAuthentication signs the user out of the app and starts the flow again. The module decodes the token and makes no check of its signature. The token came to the pod straight from the token address.

Development mode skips the sign-in. With NODE_ENV at any value other than production, checkAuthentication lets every request through. That is how the page is built on a workstation with no cluster.

Where the client comes from
#

The app is a confidential client of the identity provider: it has an id and a secret. The deploy script generates the secret and stores it in a secret of the namespace. A Job then registers the client, with the callback address of the app, the scope of the table above and the method client_secret_basic. The pod reads id and secret from a read-only mount.

Deploying Into a MAS Namespace shows what happens when the registered secret and the mounted secret differ: the sign-in ends with “Authentication failed”.

One setting, and an Internal Server Error
#

The app uses a public address and an inside address of the identity provider. The browser is sent to the public one. The app itself exchanges the code for the token at the service inside the cluster. These are the lines of the manifest for it. We left out one line, the issuer, which repeats the first address:

# browser-facing addresses of the suite's sign-in; they differ by routing mode (deploy.sh)
- { name: AUTH_OIDC_URI, value: __AUTH_OIDC__ }
- { name: AUTH_API_URI, value: __AUTH_BASE__/api/auth }
- { name: AUTH_LOGOUT_URI, value: __AUTH_BASE__/ibm_security_logout }
# the token exchange goes to coreidp inside the cluster; the pod does not trust the
# certificate chain it sees at the public address
- { name: TOKEN_URL, value: https://coreidp.__NS__.svc/oidc/endpoint/MaximoAppSuite/token }
- { name: INTERNAL_AUTH_API_URI, value: https://coreidp.__NS__.svc/api/auth }
# trust the internal CA, for the token exchange, the internal API and Manage
- { name: NODE_EXTRA_CA_CERTS, value: /etc/ssl/certs/mascore-cert/ca.crt }

We set the token address to the public one on purpose and signed in again. The browser stopped at the callback address of the app with the text “Internal Server Error”, and every later request to the app answered 500.

The log of the pod had no line about it. We looked for the cause from inside the pod. A request to the public address of the suite failed there with “self signed certificate in certificate chain”. The setting NODE_EXTRA_CA_CERTS was in place the whole time: it names the authority of the suite’s internal certificates, and the pod trusts the service inside the cluster with it.

We set the token address back, and the sign-in worked again.

The session is the app’s own
#

The session of the skeleton lives in the memory of one pod. The session library says so itself: the log of our pod has its warning that the memory store is not designed for production and will not scale past a single process.

We met two effects of the app keeping its own session.

The app’s session outlived a change of user in the suite. We signed in to the suite as an administrator, opened the app, and then signed in to the suite as two other users, one after the other. The app answered all three with the administrator’s data. Its cookie was still there, and its session with it.

The logout address of the app ends the app’s session and sends the browser to the logout of the suite. The skeleton has an address logmeout for it. We called it and landed on the logout page of the suite. After that, each user got that user’s own answers.

Our product mas-tools.com Data Import goes further. It Works as You describes an app whose session follows the session of the suite, for a sign-out in another tab and for another user in the same browser.

What we take from it
#

  • Send the browser to the public address and the pod to the service inside the cluster. With the token address on the public route, our sign-in ended in a 500.
  • We found no log line for that failure. We found the cause by asking the address from inside the pod.
  • Give the session cookie the name and the path of the app. Under path routing, every app of the suite is on one host.
  • Decide what the app does when the user changes in the suite. The skeleton kept the old session until its logout address was called.

What to read next#

Authorization: Reusing Maximo’s Signature Options is the step after the sign-in: may this user use the app? Anatomy of a MAS Companion App shows the same first redirect on a released app.