Login into Sitecore Programmatically

Sitecore is a CMS based tool mainly used for Content Management purpose. Most of the times you will Login to Sitecore through the web-based Sitecore Login interface to perform content authoring. In this article, we will see How to Login Programmatically into Sitecore.

Login into Sitecore Programmatically

At certain times if you want to connect Sitecore API with web service or any other application you might have to login into Sitecore programmatically  before performing any database operations.

Recommended Articles

Step 1:

Use a Security Disabler to make the program run in the context of an authenticated user.

using(new Sitecore.SecurityModel.SecurityDisabler()) {
  // Logic Goes Here
}

Step 2:

Authenticate Sitecore User Programmatically. The authentication process is very simple in Sitecore as there is an API Sitecore.Security.Authentication.AuthenticationManager.Login

public static bool AuthenticateUser(string username, string password) {
  bool isAuthenticated = false;
  try {
    if (Sitecore.Security.Accounts.User.Exists(username)) {
      isAuthenticated = Sitecore.Security.Authentication.AuthenticationManager.Login(username, password, false);
    }
  } catch (Exception ex) {
    isAuthenticated = false;
  }
  return isAuthenticated;
}

Step 3:

If the Authentication returns true then use the UserSwitcher to get the specific control on the Sitecore Database and items.

 if (SitecoreUtility.AuthenticateUser(SitecoreUserName, SitecorePassword)) {
   Sitecore.Security.Accounts.User user =
     Sitecore.Security.Accounts.User.FromName(SitecoreUserName, true);
   using(new Sitecore.Security.Accounts.UserSwitcher(user)) {

     //Write your Logic here
   }
 }
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like