WCF PrincipalPermission

In my previous post, I was using PrincipalPermissionAttribute, the limitation of this solution is, developers have to hardcode the authorized role list into code. To improve it, we can call Demand() method explicitly.

// WCF Service
public void DeleteEmailRole(EmailRoleDto emailRoleDto)
// Will throw SecurityException and then WCF will convert it to SecurityAccessDeniedException
// to WCF client side, so we don't need add SecurityException to Contract, because it will not be
    // caught as FaultException.

public class AuthorizationChecker : IAuthorizationChecker
private readonly IAuthRoleRepository _authRoleRepository;

public AuthorizationChecker(IAuthRoleRepository authRoleRepository)
_authRoleRepository = authRoleRepository;

/// <summary>
/// Can be used by UI to enable/disable buttons/menus.
/// </summary>
public bool IsCurrentUserAllowedTo(string serviceName)
catch (SecurityException)
return false;

return true;

public void CheckPermissionForCurrentUserOn(string serviceName)
IPermission permissionSet = null;

foreach (var role in
var permission = new PrincipalPermission(null, role);
permissionSet = permissionSet == null ?  permission : permissionSet.Union(permission);

// Demand will throw Security exception if user has no permission defined in authRoleRepository.
if (permissionSet != null) permissionSet.Demand();

// Client code
protected void HandleException(Exception e)

if (e is SecurityAccessDeniedException)
_messageBox.Show("Sorry you don't have permission to this method.\n" + e.Message);
throw e;



One thought on “WCF PrincipalPermission

  1. Pingback: Extened service behavior to check authorization « maonet technotes

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s