SecurityDisabler or UserSwitcher

As a Sitecore developer, we often encounter security restrictions. To overcome these, Sitecore Developers can use SecurityDisabler or UserSwitcher. In this blog post, we will examine the difference between the two and which one is recommended by Sitecore.

SecurityDisabler

SecurityDisabler as the name implies, disable all security restriction completely. If there is security limiting access to content or certain functionality, SecurityDisabler disable or override all of that.

CSharp version of SecurityDisabler

   using (new Sitecore.SecurityModel.SecurityDisabler())
   {
      //Your code here:
   }

Sitecore Powershell Extension (SPE) version of SecurityDisabler

New-UsingBlock(New-Object -TypeName "Sitecore.SecurityModel.SecurityDisabler"){
    # Add your script here
}

UserSwitcher

UserSwitcher execute the code under the context of the specific user. With UserSwitcher, you can limit what the code can perform (in terms of permission). As an example, you have a user called “ServiceAccount” with read and write access permission to specific items in the content tree. If the code performs a delete action, an AccessDeniedException is thrown . If SecurityDisabler is use in this scenario, the delete action is successful.

CSharp version of UserSwitcher

string scUser = @"sitecore\systemaccount";
using (new Sitecore.Security.Accounts.UserSwitcher(scUser))
{
    //Your code here...
} 

Sitecore Powershell Extension (SPE) version of UserSwitcher

$serviceaccount = [Sitecore.Security.Accounts.User]::FromName("sitecore\serviceaccount", $false)
[Sitecore.Security.Accounts.UserSwitcher]::Enter($serviceaccount)

# YOUR CODE HERE

[Sitecore.Security.Accounts.UserSwitcher]::Exit()

Best practice SecurityDisbler or UserSwitcher?

Sitecore recommends the use of UserSwitcher over SecurityDisabler. The reason behind this is that:

  • UserSwitcher gives security management into your code.
  • UserSwitcher gives you more sense of control on what your code can do in terms of permission.
  • SecurityDisabler will not give permission checks at all, which is a security concern.
  • SecurityDisabler will mess up the audit trail. Anything done with the SecurityDisabler will show up as being done by the sitecore\Anonymous role.

Don’t forget my other blog posts. Please leave your comment below.

Salamat po (Thank you)!

Sitecore Community.

This Post Has 5 Comments

  1. Glenn

    Nice article. Good job!

  2. Hanz Enriquez

    Good Article. 🙂

  3. Sonny

    Nice. Very helpful especially to those new to Sitecore. 👌

  4. Carl

    Thanks for sharing! This is really helpful.

Leave a Reply

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