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

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

Sending a Message in Exchange Online via REST from an Arduino MKR1000

This is part 2 of my MKR1000 article, in this previous post  I looked at sending a Message via EWS using Basic Authentication.  In this Post I'll look at using the new Outlook REST API  which requires using OAuth authentication to get an Access Token. The prerequisites for this sketch are the same as in the other post with the addition of the ArduinoJson library  https://github.com/bblanchon/ArduinoJson  which is used to parse the Authentication Results to extract the Access Token. Also the SSL certificates for the login.windows.net  and outlook.office365.com need to be uploaded to the devices using the wifi101 Firmware updater. To use Token Authentication you need to register an Application in Azure https://msdn.microsoft.com/en-us/office/office365/howto/add-common-consent-manually  with the Mail.Send permission. The application should be a Native Client app that use the Out of Band Callback urn:ietf:wg:oauth:2.0:oob. You need to authorize it in you tenant (eg build a small ap

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
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.