Sitecore check access and roles programatically

The Sitecore security model have changed over time, but the general API to check security access and roles have been stable for many many years.

CHECK IF USER HAS ACCESS TO AN ITEM:

To check if a user have access to a Sitecore item:

// Get Sitecore item
var item = Sitecore.Context.Database.GetItem("/sitecore/content/home/item");

// Check if the current context user 
// have read access to the item
bool canRead = item.Access.CanRead();

// Check if a named user have read access
// to an item
using (new Sitecore.Security.Accounts.UserSwitcher(@"extranet\username", true))
{
  bool canRead = item.Access.CanRead();
}

CHECK IF USER HAVE A CERTAIN ROLE:

The Sitecore User object has a Roles property, but this property does only list the immediate roles, not the roles obtained from roles-in-roles. To check for all roles, you need to use the IsInRole property:

using Sitecore.Security.Accounts;

// Get the role to check
// Remember to prefix the role name with 
// the domain name
Role role = Role.FromName(@"extranet\rolename");

// Check if user have the role
var isInRole = Sitecore.Context.User.IsInRole(role);

MORE TO READ:

Advertisements

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, c#, General .NET, Sitecore 6, Sitecore 7, Sitecore 8, Sitecore 9 and tagged , , , . Bookmark the permalink.

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.