Add user to organization from email domain

We are looking into using organisations to setup authentication on a dashboard we provide to our business partners. Is it possible to have users automatically added to an organisation according to their email domain?

For example, we have organization1, organization2 and organization3. We want to allow users to login to our dashboard with google, and be be automatically assigned to organization1 if their email is @organization1.com, etc.

How can we achieve this?

Thanks

Hi @pepin,

Welcome to the Auth0 Community!

I understand you would like to programmatically assign users to different organizations based on their email domain.

To do so, you could use the Management API Add member to Organization endpoint in an Auth0 Post-Login-Action. In the code, you will need to check if the user’s email matches a particular domain and assign them to the Organization accordingly.

Below is the code needed to accomplish this:

exports.onExecutePostLogin = async (event, api) => {
  const ManagementClient = require('auth0').ManagementClient;

  const management = new ManagementClient({
      domain: event.secrets.domain,
      clientId: event.secrets.client_id,
      clientSecret: event.secrets.client_secret,
  });

  const user_domain = event.user.email.split('@')[1]
  if(user_domain == 'example.com'){
    var params =  { id :'YOUR_ORG_ID'};
    var data = { members: [ event.user.user_id ] }
    management.organizations.addMembers(params, data, function (err) {
    if (err) {
        // Handle error.
    }
    });
  }
  else{
    //pass
  }
};

I have tested this and can confirm that it works.

Lastly, please see How can I use the Management API in Actions? FAQ for more details.

Please let me know if you have additional questions.

Thank you.