Restrict API to a Specific Organization

Overview

Some customers may want to restrict an API in Auth0 to a specific Organization. One possible use case is an internal API that should only be accessible to an organization that contains the customers’ backend developers.

Applies To

  • API Calls
  • Multiple Organizations
  • Specific Organization

Solution

The following ‘post-login’ action will restrict an API to be accessible only for the users within the specified organization:

exports.onExecutePostLogin = async (event, api) => {

  const organization_id = event?.organization?.id;
  const audience        = event?.resource_server?.identifier;
  const restricted_org  = ''; // FILL IN ORGANIZATION TO RESTRICT API TO
  const restricted_api  = ''; // FILL IN API TO RESTRICT

  if (audience === restricted_api) { 
    console.log(event.organization);
    if ( !(organization_id === restricted_org) ) {
      return api.access.deny("This API can only be accessed by users in organization id: " + organization_id);
    }
  }
}

Related References