Unauthorized for valid users

I’m running into an issue where okta will hit our callback and we get a 401 (intermittently).

It fails with this response, however the user has access and has been successfully validated.
${API_URL}/api/auth/okta/callback/login?code=7-YCBJgztpMGic-XNLxj&state=4ff151e5-2969-47e2-8501-4445440f0d08

(this only recently just started happening, was working without any issues before)

We are using internal JWT tokens to authenticate users after we get their user info from Okta… but, this case, it doesn’t even hit our service endpoints since oidc middleware kicks back 401.

Web API src:

const session = require('express-session');
const { ExpressOIDC } = require('@okta/oidc-middleware');

const users = require('../data/users');
const jwt = require('./jwt');

const { logger } = require('../utils/common');

const {
  PORT,
  OKTA_CLIENT_ID,
  OKTA_CLIENT_SECRET,
  OKTA_ISSUER,
  OKTA_TESTING_DISABLEHTTPSCHECK,
  OKTA_API_BASE_URL,
  OKTA_APP_BASE_URL,
  OKTA_SESSION_SECRET,
  OKTA_SCOPE,
} = require('../constants');

const initialize = (app) => {

  app.use(session({
    secret: OKTA_SESSION_SECRET,
    resave: true,
    saveUninitialized: false
  }));

  const oidc = new ExpressOIDC({
    issuer: OKTA_ISSUER,
    client_id: OKTA_CLIENT_ID,
    client_secret: OKTA_CLIENT_SECRET,
    appBaseUrl: OKTA_API_BASE_URL,
    scope: OKTA_SCOPE,
    testing: {
      disableHttpsCheck: OKTA_TESTING_DISABLEHTTPSCHECK
    },
    // You can't have nested routes
    // https://github.com/okta/okta-oidc-js/issues/207
    routes: {
      login: {
        path: '/api/auth/okta/login'
      },
      logout: {
        path: '/api/auth/okta/logout'
      },
      loginCallback: {
        path: '/api/auth/okta/callback/login',
        afterCallback: '/api/auth/okta/jwt'
      },
      logoutCallback: {
        path: '/api/auth/okta/callback/logout',
        afterCallback: '/logout'
      },
    },
  });

  // okta
  app.use(oidc.router);

  app.get('/api/auth/okta/jwt', oidc.ensureAuthenticated(), async (req, res) => {
    const ui = req.userContext && req.userContext.userinfo;
    try {
      let u = false;

      // check to see if this user already exists
      // try {
      u = await users.findOne(ui.email.toLowerCase());
      // } catch (error) {
      // }

      // update the name for this user if it's changed or hasn't been set
      try {
        let name = `${ui.given_name} ${ui.family_name}`;
        await users.setName(u.id, name);
        u = Object.assign(u, { name });
      } catch (error) {
        console.log(error);
      }

      // set last login date for this user
      try {
        await users.setLastLogin(u.id);
      } catch (error) {
        console.log(error);
      }

      try {
        let tokens = jwt.getTokens(u);
        res.redirect(307, `${OKTA_APP_BASE_URL}/login?access=${JSON.stringify(tokens.access)}&refresh=${JSON.stringify(tokens.refresh)}`);
        return;
      } catch (error) {
      }
    } catch (error) {
    }
    res.redirect(307, `${OKTA_APP_BASE_URL}/user-not-valid?email=${ui.email}&name=${ui.given_name} ${ui.family_name}`);
  });

  oidc.on('ready', () => {
    logger.debug(`listening on ${PORT}`);
    app.listen(PORT);
  });

  oidc.on('error', err => {
    // An error occurred with OIDC
    throw err;
  });
};


module.exports = {
  initialize
};

Typically, if the user makes a second attempt after this failure, they login just fine and don’t hit this 401 error.

Hi @krashid

When this error happens, do you see an outbound request to Okta? Also, were there any recent firewall or network changes?

From a first glance, the Unauthorized error message appears because the SDK is unable to send the authorization code successfully back to Okta for a set of JWTs.

Nope, no firewall or network changes (running in AWS lambda behind API gateway). I’m not able to see any network requests as this is all occurring server side (unless there is some logging functionality that I can turn on that I don’t know about)

Cheers

Hi @krashid

Can you please open a support case with us during your business hours by sending us an email to developers@okta.com, mentioning the Okta subdomain and client id of the application used? One of our Developer Support Engineers will further assist you in narrowing down the issue.

I have reached out, but haven’t received any help.

I still haven’t received any help on this.