Workaround for MFA error when using getAccessTokenSilently with React

Hi,

When using getAccessTokenSilently from the @auth0/auth0-react sdk I encountered frequent 403 errors with the error Type: Failed Silent Auth; Description: Multifactor authentication required

MFA is required but I also needed to be able to get an access token to call APIs, without prompting the user a second time after they already had authenticated with MFA previously. I had some trouble that took me several hours to figure out and I wanted to post my findings since current threads on this topic were closed, and I couldn’t find help in the Auth0 docs, I hope I can save someone else the trouble.
In our case we were using Refresh tokens as well. The solution below worked for me:

This is a working Auth0 Action similar to the same rule (which appears to be preferred over Rules)

  1. Add an Auth0 Action in the Auth0 Management panel
  2. use this code:
exports.onExecutePostLogin = async (event, api) => {
  if (event.client.name !== <your apps client name>) {
    return;
  }

  const isRefreshTokenProtocol =
    event?.transaction?.protocol === "oauth2-refresh-token";
  let authMethods = [];
  if (event.authentication && Array.isArray(event.authentication.methods)) {
    authMethods = event.authentication.methods;
  }
  const isMFAAuthenticated = Boolean(
    authMethods.find((method) => method.name === "mfa")
  );

  if (isMFAAuthenticated || isRefreshTokenProtocol) {
    api.multifactor.enable("none");
  }
};
1 Like

Hi @zachary.willard

Many thanks for posting your findings here, it is much appreciated.

Warm regards.

1 Like

Thank you @zachary.willard ! For those visiting this thread the solution is posted in the first post in the thread. Thank you!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.