Dynamics CRM Developer Tip O’ the Day: Does the user have a security role?

Occasionally, when working with .NET and the Dynamics CRM SDK, you’ll find a need to see if the current user has a particular security role. This is helpful before performing any operation that may result in a security exception.

Here is a small method to handle that call:

public bool UserHasSecurityRole(OrganizationService service, string securityRoleName)
{
    var whoami = (WhoAmIResponse)service.Execute(new WhoAmIRequest());

    using (var context = new CrmOrganizationServiceContext(service))
    {
        var query = (from sr in context.CreateQuery<SystemUserRoles>()
                        join r in context.CreateQuery<Role>() 
                           on sr.RoleId.Value equals r.RoleId.Value
                        where r.Name == securityRoleName
                        where sr.SystemUserId == whoami.UserId
                        select sr).ToList();

        return query.Count > 0;
    }
}

and it is used like this:

var isSystemAdministrator = UserHasSecurityRole(service, "System Administrator");

How It Works

We first perform a WhoAmI request to get the ID of the current user.

Next, the method uses the Dynamics CRM LINQ (Language Integrated Query) provider to query the SystemUserRole and Role entities where the Role Name is equal to the security role and the User ID is that of the current user.

If there are any records returned at all, then that user has the security role we were looking for.

A true or false is returned depending on that number.