Quantcast
Channel: Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 285

Sitecore check access and roles programatically

$
0
0

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:


Viewing all articles
Browse latest Browse all 285

Trending Articles