Checking if a user has System admin role

Find below a C# method to check if an specified user(Sent as parameter) has System Admin role. The method will return true if so. Otherwise, it will return false.

///
/// Verify if a User has System Admin role. Return true if so, false in other case.
///
public bool IsSystemAdmin(Guid userID, IOrganizationService service)
{
// All MS Dynamics CRM instances share the same System Admin role GUID.
// Hence, we can hardode it as this will not represent a security issue
Guid AdminID = new Guid("627090FF-40A3-4053-8790-584EDC5BE201");

// Defining our primary Entity for the query
var Query = new QueryExpression("role");

// Adding validation to search based on our System Admin Role GUID
Query.Criteria.AddCondition("roletemplateid", ConditionOperator.Equal, AdminID );

// Adding a Link to SystemUserRoles Entity so we can check the User roles
var link = Query.AddLink("systemuserroles", "roleid", "roleid");

// To filter only roles of the giving user
link.LinkCriteria.AddCondition("systemuserid", ConditionOperator.Equal, userID);

// Return result
bool HasSystemAdminRole = service.RetrieveMultiple(Query).Entities.Count > 0;
return HasSystemAdminRole;
}

Hope it helps.

Advertisements

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s