Welcome to my blog, stay tunned :
Home | Blogs | Stephane Eyskens's blog

Preventing external sharing with the entire external world in SharePoint Online


As you know, external sharing can be controlled at site collection level to allow or not sharing with external users. However, until now, if you allow sharing, it is by default with the entire world. The sharing invitation will be sent to the e-mail address of the person you're sharing the site/document with. When that person clicks on the invite, she is invited to login with either a Microsoft Account, either an Organizational Account which is created in the AAD. Afterwards, the user is added to the group/assigned direct permissions.

A while ago, I proposed a workaround http://www.silver-it.com/node/177 that consisted in tweaking a little bit the UI with JavaScript so that the People Picker control would only resolve users belonging to an allowed domain. I knew it was a workaround and not a long term solution and this proved true because it’s not working anymore  since Microsoft has completely changed the way the sharing UI works. However, for those who would still require to restrict sharing to only predefined partners, here is an alternative approach that works:

  • Define a list of allowed domains in a database/central SharePoint List. You can map allowed domains per site collection for instance
  • Develop a Remote Event Receiver that you add to Site.Receivers that listens to RoleAssignmentAdding and GroupUserAdding so that you control direct permission assignment to users and adding users to groups.
  • In the RER, check the domain of the user to whom the invite is sent and reject the event in case it’s not part of the allowed domains

This works very well and allow you to control who you want to share with, some drawbacks however:

  • When sharing a document, in case your RER rejects it, SharePoint shows an error message such as “Unexpected error…”, although the RER returns a user friendly message via the SPRemoteEventResult object but sharing is blocked
  • What the RER blocks is adding a user to a group and assigning direct permissions to users with an invalid domain. However, in case of direct permission assignment, the invite is still sent by e-mail…but users can’t of course access the resource, so at least, your data remains protected against unexpected audience
  • The external user is still added to AAD, so you need to get rid of it via the Graph API.

Tip for development and deployment:

  • Don’t use an App to deploy the RER. If you want to stop controlling sharing, you might end up with orphan RER when the App is removed (in case of problems). App event receivers can only be removed by the App itself, not via CSOM which can be problematic
  • Use CSOM to add/remove RER to the site collections.

Of course, if you can afford to wait until Microsoft addresses this problem, it's even better.

Happy Coding