RoleAssignmentAdding event receiver in SharePoint 2013 does not show error page with CancelWithError
This post is a contribution from Aaron Miao, an engineer with the SharePoint Developer Support team
SharePoint 2013 SPSecurityEventReceiver provides methods to trap events that are raised for security. Tim Ferro’s this blog provides great details missing from MSDN document about the class.
This blog is to provide one detail about the issue of canceling RoleAssignmentAdding event.
With the code below,
public override void RoleAssignmentAdding(SPSecurityEventProperties properties)
{
base.RoleAssignmentAdding(properties);
// more code here: if user is “everyone” cancel the adding
string errMsg = "This user is not allowed to be added to this site";
properties.ErrorMessage = errMsg;
properties.Status = SPEventReceiverStatus.CancelWithError;
}
when adding a user from _layouts/15/user.aspx page, like this (adding “everyone” to a team site with explicitly specifying Read permission):
You would expect an (out-of-box) error page shows up with the error you set like below.
This works just fine with GroupUserAdding event (adding a user without explicitly specifying permission). However the error page won’t show up when canceling RoleAssignmentAdding event. This due to a defect in SharePoint product. The problem will be likely addressed in next release of SharePoint.
Fortunately you can work around the issue by creating a custom error page. This blog has all the details about SharePoint 2013 event receiver redirect.
Code (as described in the blog) like below should lunch your custom error page to notify users.
private readonly HttpContext _currentContext;
public UserAddingEventReceiver(ISecurityEventConfig config)
{
_currentContext = HttpContext.Current;
}
public override void RoleAssignmentAdding(SPSecurityEventProperties properties)
{
base.RoleAssignmentAdding(properties);
string url = new StringBuilder("CustomErrorPage.aspx");
string urlRedirect = null;
// more code here: if user is “everyone” cancel the adding
string errMsg = "This user is not allowed to be added to this site";
properties.ErrorMessage = errMsg;
properties.Status = SPEventReceiverStatus.CancelWithError;
bool flag = SPUtility.DetermineRedirectUrl(url.ToString(), SPRedirectFlags.RelativeToLayoutsPage, _currentContext, null, out urlRedirect);
_currentContext.Response.Redirect(urlRedirect + "&Error=" + errMsg, true);
}
Comments
- Anonymous
December 21, 2014
I can't even get this event to fire at all. Admittedly I'm attaching it as a remote event receiver, but surely it should work in that case too? Basically I want to be notified when sharing is changed on documents on a remote farm. I've installed the event receiver (at the list level) for ItemAdding and that works fine, but nothing is fire for RoleAssignmentAdding (or Added). - Anonymous
December 21, 2014
Found the problem, you need to attach these events to a web, not a list.