Skip to main content

Setting and Understanding Folder Permissions in Exchange Web Services

One of the more challenging things you may want to do when writing code that is going to run against an Exchange 2007 mailbox is to set and modify Folder permissions on a mailbox folder or a public folder. I’d thought I’d share my efforts and what I learnt over the last week of trying to do this (thanks to David Claux for helping me get over my issues with custom permissions). One of the features added to SP1 in Exchange 2007 is the ability to set folder permissions and also folder delegates. This is a pretty cool feature but one you do need to make sure you understand before you dive in. Before you start its a good idea to understand the permissions your want to modify to ensure your code is going to work as expected and avoid any unwanted ACL changes.

Let’s start by looking at the permissions that can be set on a folder via EWS

CanCreateItems
ReadItems
DeleteItems
EditItems
CanCreateSubFolders
IsFolderContact
IsFolderOwner
IsFolderVisible

With Exchange 2007/Outlook2007 there where Permissions added to support the new freebusy detail features in Outlook and Exchange. There’s some good information about these on Stephen Griffin's Blog . These new permissions are only valid for a calendar folder. Overlaying these based folder permissions are the Roles that a user would generally assign in Outlook. Now these Roles are just certain combinations of the above Permissions. The following are the roles you would normally see set on a folder if you’re looking in Outlook

Author
Contributor
Custom
Editor
None
NoneditingAuthor
Owner
PublishingAuthor
PublishingEditor
Reviewer

On a calendar folder you have the following additional roles to support freebusy detail

FreeBusyTimeAndSubjectAndLocation
FreeBusyTimeOnly

Now let’s look at an example of setting the calendar folder permissions using EWS. Generally when you are setting permissions you’ll be modifying the permissions on an already existing Exchange Store object. So you will be either adding an additional Access Control Entry to the permissions list or modifying the rights or an existing ACE.

In EWS calendar folder permissions are represented by the CalendarPermissionSetType object so to modify the permissions on an existing folder you need to modify the Permission Set property using an updateitem operation. Sounds easy right well this is where the complications begin.

When you use an UpdateItem operation to update a property on a folder that property you update will overwrite the existing store property. Because the whole PermissionSet is represented as one property you can’t just write the changes with an UpdateItem operation. If you do this you will end up deleting all your existing ACE’s and end up only with the changes you’re trying to make. So to cater for this you first need to get the existing CalendarPermissionSet using a GetFolder operation, you then need to create a new CalendarPermissionSet that contains all the ACE’s from the existing CalendarPermissionSet with whatever modifications you want and then post this new CalendarPermissionSet to overwrite the existing set. Now here’s a precautionary tale don’t do what I tried to which was to try and just make changes to the existing CalendarPermissionSet object you retrieve with GetFolder operation and then post this back.

The reason this could fail is also a little complicated but there are a few important points to understand.

When you include a calendarPermission in a CalendarPermissionSet you have to set the CalendarPermissionLevel. These Levels relate to the Outlook Roles I mentioned previously if these roles are set to anything other than Custom you must make sure you don’t include setting any of the base rights. So basically you can set something like the CalendarPermissionLevel to PublishingAuthor or you can set the CalendarPermissionLevel to custom and then set each of the base rights like CanCreateItems,ReadItems etc. If you try to set CalendarPermissionLevel to PublishingAuthor and also set the base rights (including the foldercontact and folderowner setting) EWS will reject the changes you’re trying to make as invalid.

Now when you get the permissionset using a GetFolder operation EWS will return a fully populated CalendarPermission object for each ACE in the Set even if the CalendarPermissionLevel isn’t set to custom. So if you try to use one of these calendarPermissions that had a CalendarPermissionLevel set to something other than custom it will cause your code to error out because it breaks the rule I mentioned in the last paragraph.

So from a coding perspective to make this work you should build a new CalendarPermissionLevel object based on the existing object with some logic to verify the CalendarPermission your including in the set is going to be valid. The logic I came up with was you can copy any of the existing custom CalendarPermissionLevel objects okay into the new CalendarPermissionSet object but for any other role you need to create a new CalendarPermission object and just copy the userid and CalendarPermissionLevel from the existing CalendarPermission.

The one thing to be careful of if you are setting Public Folder permission with EWS and you have set custom folder contacts is you may in some situations lose your custom contact folder setting if you set permissions using EWS and you don’t use the Custom Level.

So to put this all together in a code sample the following piece of code will change the default permissions on a user’s calendar from none to editor. I’ve put a download of this code here the code itself looks like.

static void Main(string[] args)
{
// Create the binding and set the credentials
ExchangeServiceBinding esb = new ExchangeServiceBinding();
esb.RequestServerVersionValue = new RequestServerVersion();
esb.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007_SP1;
ServicePointManager.ServerCertificateValidationCallback =
delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
// Replace this line with code to validate server certificate.
return true;
};

esb.Credentials = new NetworkCredential("username", "password", "domain");
esb.Url = @"https://servername/EWS/Exchange.asmx";
setcalperm(esb);

}
static void setcalperm(ExchangeServiceBinding esb)
{

DistinguishedFolderIdType cfCurrentCalendar = new DistinguishedFolderIdType();
cfCurrentCalendar.Id = DistinguishedFolderIdNameType.calendar;

FolderResponseShapeType frFolderRShape = new FolderResponseShapeType();
frFolderRShape.BaseShape = DefaultShapeNamesType.AllProperties;

GetFolderType gfRequest = new GetFolderType();
gfRequest.FolderIds = new BaseFolderIdType[1] { cfCurrentCalendar };
gfRequest.FolderShape = frFolderRShape;


GetFolderResponseType gfGetFolderResponse = esb.GetFolder(gfRequest);
CalendarFolderType cfCurrentFolder = null;
if (gfGetFolderResponse.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Success)
{

cfCurrentFolder = (CalendarFolderType)((FolderInfoResponseMessageType)gfGetFolderResponse.ResponseMessages.Items[0]).Folders[0];

}
else
{//handle error
}

UserIdType auAceUser = new UserIdType();
auAceUser.DistinguishedUserSpecified = true;
auAceUser.DistinguishedUser = DistinguishedUserType.Default;

CalendarPermissionSetType cfCurrentCalPermsionsSet = cfCurrentFolder.PermissionSet;
CalendarPermissionSetType cfNewCalPermsionsSet = new CalendarPermissionSetType();
cfNewCalPermsionsSet.CalendarPermissions = new CalendarPermissionType[cfCurrentCalPermsionsSet.CalendarPermissions.Length] ;
for(int cpint=0;cpint < cfCurrentCalPermsionsSet.CalendarPermissions.Length;cpint++){
if (cfCurrentCalPermsionsSet.CalendarPermissions[cpint].UserId.SID == auAceUser.SID)
{
cfNewCalPermsionsSet.CalendarPermissions[cpint] = new CalendarPermissionType();
cfNewCalPermsionsSet.CalendarPermissions[cpint].UserId = cfCurrentCalPermsionsSet.CalendarPermissions[cpint].UserId;
cfNewCalPermsionsSet.CalendarPermissions[cpint].CalendarPermissionLevel = CalendarPermissionLevelType.Reviewer;
}
else
{
//Copy old ACE
if (cfCurrentCalPermsionsSet.CalendarPermissions[cpint].CalendarPermissionLevel == CalendarPermissionLevelType.Custom)
{
cfNewCalPermsionsSet.CalendarPermissions[cpint] = cfCurrentCalPermsionsSet.CalendarPermissions[cpint];
}
else
{
cfNewCalPermsionsSet.CalendarPermissions[cpint] = new CalendarPermissionType();
{
cfNewCalPermsionsSet.CalendarPermissions[cpint].UserId = cfCurrentCalPermsionsSet.CalendarPermissions[cpint].UserId;
cfNewCalPermsionsSet.CalendarPermissions[cpint].CalendarPermissionLevel = cfCurrentCalPermsionsSet.CalendarPermissions[cpint].CalendarPermissionLevel;
}
}
}

}


CalendarFolderType cfUpdateCalFolder = new CalendarFolderType();
cfUpdateCalFolder.PermissionSet = cfNewCalPermsionsSet;

UpdateFolderType upUpdateFolderRequest = new UpdateFolderType();

FolderChangeType fcFolderchanges = new FolderChangeType();

FolderIdType cfFolderid = new FolderIdType();
cfFolderid.Id = cfCurrentFolder.FolderId.Id;
cfFolderid.ChangeKey = cfCurrentFolder.FolderId.ChangeKey;

fcFolderchanges.Item = cfFolderid;

SetFolderFieldType cpCalPerms = new SetFolderFieldType();
PathToUnindexedFieldType cpFieldURI = new PathToUnindexedFieldType();
cpFieldURI.FieldURI = UnindexedFieldURIType.folderPermissionSet;
cpCalPerms.Item = cpFieldURI;
cpCalPerms.Item1 = cfUpdateCalFolder;

fcFolderchanges.Updates = new FolderChangeDescriptionType[1] { cpCalPerms };
upUpdateFolderRequest.FolderChanges = new FolderChangeType[1] { fcFolderchanges };

UpdateFolderResponseType ufUpdateFolderResponse = esb.UpdateFolder(upUpdateFolderRequest);
if (ufUpdateFolderResponse.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Success)
{
Console.WriteLine("Permissions Updated sucessfully");
}
else
{
// Handle Error

}

}

Popular posts from this blog

Testing and Sending email via SMTP using Opportunistic TLS and oAuth in Office365 with PowerShell

As well as EWS and Remote PowerShell (RPS) other mail protocols POP3, IMAP and SMTP have had OAuth authentication enabled in Exchange Online (Official announcement here ). A while ago I created  this script that used Opportunistic TLS to perform a Telnet style test against a SMTP server using SMTP AUTH. Now that oAuth authentication has been enabled in office365 I've updated this script to be able to use oAuth instead of SMTP Auth to test against Office365. I've also included a function to actually send a Message. Token Acquisition  To Send a Mail using oAuth you first need to get an Access token from Azure AD there are plenty of ways of doing this in PowerShell. You could use a library like MSAL or ADAL (just google your favoured method) or use a library less approach which I've included with this script . Whatever way you do this you need to make sure that your application registration  https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-

How to test SMTP using Opportunistic TLS with Powershell and grab the public certificate a SMTP server is using

Most email services these day employ Opportunistic TLS when trying to send Messages which means that wherever possible the Messages will be encrypted rather then the plain text legacy of SMTP.  This method was defined in RFC 3207 "SMTP Service Extension for Secure SMTP over Transport Layer Security" and  there's a quite a good explanation of Opportunistic TLS on Wikipedia  https://en.wikipedia.org/wiki/Opportunistic_TLS .  This is used for both Server to Server (eg MTA to MTA) and Client to server (Eg a Message client like Outlook which acts as a MSA) the later being generally Authenticated. Basically it allows you to have a normal plain text SMTP conversation that is then upgraded to TLS using the STARTTLS verb. Not all servers will support this verb so if its not supported then a message is just sent as Plain text. TLS relies on PKI certificates and the administrative issue s that come around certificate management like expired certificates which is why I wrote th

The MailboxConcurrency limit and using Batching in the Microsoft Graph API

If your getting an error such as Application is over its MailboxConcurrency limit while using the Microsoft Graph API this post may help you understand why. Background   The Mailbox  concurrency limit when your using the Graph API is 4 as per https://docs.microsoft.com/en-us/graph/throttling#outlook-service-limits . This is evaluated for each app ID and mailbox combination so this means you can have different apps running under the same credentials and the poor behavior of one won't cause the other to be throttled. If you compared that to EWS you could have up to 27 concurrent connections but they are shared across all apps on a first come first served basis. Batching Batching in the Graph API is a way of combining multiple requests into a single HTTP request. Batching in the Exchange Mail API's EWS and MAPI has been around for a long time and its common, for email Apps to process large numbers of smaller items for a variety of reasons.  Batching in the Graph is limited to a m
All sample scripts and source code is provided by for illustrative purposes only. All examples are untested in different environments and therefore, I cannot guarantee or imply reliability, serviceability, or function of these programs.

All code contained herein is provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.