Pages

Search This Blog

Showing posts with label Security. Show all posts
Showing posts with label Security. Show all posts

Sunday, January 5, 2014

All users are logged in as System Account

There is a very strange problem we were facing in which any contributor or user when logged in into SharePoint 2010 site then it started showing him / her as sharepoint\system account. This is very strange and we checked all the possible scenarios to confirm that nothing applies in my case :- 


Checked the user policy in central admin and there was nothing that was causing this issue





















Another possibility was to check if the farm admin account is operating as system account but that was also not the case.






Now another question came in my mind if this setting is not enabled then why does SharePoint showing system account at all. Strange but true. May be this setting is not at all applied on the farm account any by default it consider it as system account.



Then we checked the farm account is not set to the contributors ad account but it was correct and set to the farm admin account only





Then we checked if there is any problem with IIS pool Account and it was correctly set except that if was running as a specific user which is my farm admin account. Now I got the issue, this is the reason why all my users were being impersonated as system account. I changed it to Application user (pass-through authentication) and it solved the mystery. 






All my users are happy now as they can see their names as logged in user and and that makes me feel happy as well. It also solved lot of issues related to the authentication and access denied errors as and when user tries to perform any activity on which it doesn't has access by SharePoint.




Monday, January 9, 2012

Sharepoint Access Denied Page

Sometimes in your web part pages you may want to show the same "Access Denied" screen to the user that SharePoint provides by default when user has no access to any resource or page.


This can be easily achieved by making use of SPUtility Class of sharepoint as:


            try
            {
               //your custom code
               SPUtility.HandleAccessDenied(new Exception("not authorized"));
            }
            catch (Exception Ex)
            {
            }



Wednesday, November 30, 2011

Create and Assign Custom Permission Levels programmatically in SharePoint

Sometimes, we come across a business requirement, where in:
-     We need to create SharePoint sites on the fly (maybe using a site definition), which have their own unique permission and groups.
-     We might need to create a custom permission level for the contributors for this site, say which does not have the delete rights but all other Contributor rights as is.
-     Then we need to assign this custom permission level to Contributor group and remove the default ‘Contribute’ permission level from the site.

        /// *************************************************************************
        /// <summary>
        /// Creating & Assigning custom permission
        /// level to Contributor group of root site
        /// </summary>
        /// <param name="spWeb">SpWeb object</param>
        /// <param name="myGroup">Group on which the custom permission
        /// has to be applied</param>
        /// ************************************************************************
        private void CreateAssignCustomPermissionLevel(SPWeb spWeb, SPGroup myGroup)
        {          
            spWeb.AllowUnsafeUpdates = true;
            //Get the role definition collection for this SPWeb
            SPRoleDefinitionCollection sprdcoll = spWeb.RoleDefinitions;
           
            //Define the new custom RoleDefinition
            SPRoleDefinition roleDefinition = new SPRoleDefinition();
            roleDefinition.Name = "MyCustomRoleDefinition";
           
            //And then start giving all permisions that you want to give.
            roleDefinition.BasePermissions =
            SPBasePermissions.AddListItems
            | SPBasePermissions.EditListItems
            //| SPBasePermissions.DeleteListItems //Delete permission removed from this definition.
            | SPBasePermissions.ViewListItems
            | SPBasePermissions.OpenItems
            | SPBasePermissions.ViewVersions
            | SPBasePermissions.DeleteVersions
            | SPBasePermissions.CreateAlerts
            | SPBasePermissions.ViewFormPages
            | SPBasePermissions.BrowseDirectories
            | SPBasePermissions.ViewPages
            | SPBasePermissions.BrowseUserInfo
            | SPBasePermissions.UseRemoteAPIs
            | SPBasePermissions.UseClientIntegration
            | SPBasePermissions.Open
            | SPBasePermissions.EditMyUserInfo; 

            //Add role definition to spweb
            if (!spWeb.RoleDefinitions.Xml.ToString().Contains("MyCustomRoleDefinition"))
            {
                spWeb.RoleDefinitions.Add(roleDefinition);
                spWeb.Update();
            }          

            //Assign custom role definition to the contributor group
            SPRoleAssignment assignment = new SPRoleAssignment(myGroup);
            //Add custom role definition to the SPRoleAssignment
            assignment.RoleDefinitionBindings.Add(roleDefinition);
            //Add the custom RoleAssignment to the SPWeb.
            spWeb.RoleAssignments.Add(assignment);          

            //Once we have the custom permission level assigned to contributors group,
            //we need to remove the default 'Contribute' permission level from this web
            spWeb.RoleDefinitions.Delete("Contribute");
            spWeb.Update();
            spWeb.AllowUnsafeUpdates = false;
        }

This method can be placed in feature receiver, where this feature is activated when the site is created on the fly.

Wednesday, November 9, 2011

Encryption Decryption Class

The purpose of this class is to provide the methods which are used for Encrypting and Decrypting the Passwords and other sensitive information to be stored in database or file system.

Many a times we require to encrypt the password to store in web.config file where we can't store the password without encryption because of security reasons.

Here is the class that we can use for encryption and decryption  of string values. This class supports both the string and byte[]


public class Cryptography
    {
        public static string Encrypt(string clearText, Random randomNumber)
        {
           String salt;
           byte[] clearBytes, encryptedData;
           PasswordDeriveBytes pdb;

           salt = Convert.ToString(randomNumber.Next(9999, DateTime.Now.Millisecond * 9999));

           clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
           pdb = new PasswordDeriveBytes(salt,new byte[] {0x49, 0x76, 0x61, 0x6e,
                                         0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
           encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
           return salt.Length + salt + Convert.ToBase64String(encryptedData);

        }

        public static string Encrypt(string clearText)
        {
            Random randomNumber = new Random();
            return Encrypt(clearText, randomNumber);
        }

        public static string Decrypt(string cipherText)
        {
            if (!string.IsNullOrEmpty(cipherText))
            {
                Int32 length;
                String salt;
                byte[] cipherBytes, decryptedData;
                PasswordDeriveBytes pdb;

                length = Convert.ToInt32(cipherText.Substring(0,1));
                salt = cipherText.Substring(1, length);
                cipherText = cipherText.Substring(length + 1);
                cipherBytes = Convert.FromBase64String(cipherText);
                pdb = new PasswordDeriveBytes(salt, new byte[] {0x49, 0x76, 0x61, 0x6e,
                                              0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});

                decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
                return System.Text.Encoding.Unicode.GetString(decryptedData);
            }
            else
            {
                return string.Empty;
            }
        }

        private static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV)
        {
            MemoryStream ms;
            Rijndael alg;
            CryptoStream cs;
            byte[] decryptedData;

            ms = new MemoryStream();
            alg = Rijndael.Create();
            alg.Key = Key;
            alg.IV = IV;

            cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(cipherData, 0, cipherData.Length);
            cs.Close();

            decryptedData = ms.ToArray();
            return decryptedData;
        }

        private static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV)
        {
            MemoryStream ms;
            Rijndael alg;
            CryptoStream cs;
            byte[] encryptedData;

            ms = new MemoryStream();
            alg = Rijndael.Create();
            alg.Key = Key;
            alg.IV = IV;

            cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(clearData, 0, clearData.Length);
            cs.Close();
            encryptedData = ms.ToArray();
            return encryptedData;
        }
    }


Download code from here : http://min.us/m9KsrNOZ1



Wednesday, November 2, 2011

Sharepoint\System "User not found"

Look at the code below and if you try to run this code then it will give error while creating a site because sharepoint doesn't find super admin account



 SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(url))
                {
                    SPSiteCollection workspaces = site.WebApplication.Sites;
                    using (SPSite workspaceSite = workspaces.Add("URL", "Name", "Description", 1033, "BDR#0", SPContext.Current.Web.CurrentUser.LoginName, SPContext.Current.Web.CurrentUser.Name, SPContext.Current.Web.CurrentUser.Email))
                    {
                        return workspaceSite.ID;
                    }
                }
            });




So the workaround of this problem is to get the default site administrator of current site collection and put it in new site collection


 SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(url))
                {
                    SPUser administrator = site.RootWeb.SiteAdministrators[0];
                    SPSiteCollection workspaces = site.WebApplication.Sites;
                    using (SPSite workspaceSite = workspaces.Add("URL", "Name", "Description", 1033, "BDR#0", administrator.LoginName, administrator.Name, administrator.Email))
                    {
                       return workspaceSite.ID;
                    }
                }
            });


BDR#0 is the template Name for document center site. You can use any of the following in site creation process:

IDNameDisplay group
0GLOBAL#0Global template
1STS#0Team Site
1STS#1Blank Site
1STS#2Document Workspace
2MPS#0Basic Meeting Workspace
2MPS#1Blank Meeting Workspace
2MPS#2Decision Meeting Workspace
2MPS#3Social Meeting Workspace
2MPS#4Multipage Meeting Workspace
3CENTRALADMIN#0Central Admin Site
4WIKI#0Wiki Site
7BDR#0Document Center
9BLOG#0Blog
15SGS#0Group Work Site
16TENANTADMIN#0Tenant Admin Site
20SPS#0SharePoint Portal Server Site
21SPSPERS#0SharePoint Portal Server Personal Space
22SPSMSITE#0Personalization Site
30SPSTOC#0Contents area Template
31SPSTOPIC#0Topic area template
32SPSNEWS#0News Site
33SPSNHOME#0News Site
34SPSSITES#0Site Directory
36SPSCOMMU#0Community area template
38SPSREPORTCENTER#0Report Center
39CMSPUBLISHING#0Publishing Site
40OSRV#0Shared Services Administration Site
47SPSPORTAL#0Collaboration Portal
50SRCHCEN#0Enterprise Search Center
51PROFILES#0Profiles
52BLANKINTERNETCONTAINER#0Publishing Portal
53BLANKINTERNET#0Publishing Site
53BLANKINTERNET#1Press Releases Site
53BLANKINTERNET#2Publishing Site with Workflow
54SPSMSITEHOST#0My Site Host
56ENTERWIKI#0Enterprise Wiki
61visprus#0Visio Process Repository
90SRCHCENTERLITE#0Basic Search Center
90SRCHCENTERLITE#1Basic Search Center
2000SRCHCENTERFAST#0FAST Search Center
2764ACCSRV#0Access Services Site
2764ACCSRV#1Assets Web Database
2764ACCSRV#3Charitable Contributions Web Database
2764ACCSRV#4Contacts Web Database
2764ACCSRV#6Issues Web Database
2764ACCSRV#5Projects Web Database
3100PPSMASite#0PerformancePoint
3200BICenterSite#0Business Intelligence Center
14483OFFILE#0(obsolete) Records Center
14483OFFILE#1Records Center

Monday, June 20, 2011

Assigning Multiple values to "Person and Group" Column Type programatically

Many times we have requirement of adding multiple values to a column of type "Persons and Group" through object model. There's a way to do that very easily.

public void AssignMultipleValues(String strSemicolonSeperatedMulipleUsers)
{
   String[] userName;
   SPUser objSPUser = null;
   SPFieldUserValueCollection userCollection = new SPFieldUserValueCollection();

   if (!string.IsNullOrEmpty(strSemicolonSeperatedMulipleUsers))
  {
   userName = StringToArray(strSemicolonSeperatedMulipleUsers, ";");
   foreach (string strUserName in userName)
   {
      objSPUser = SPContext.Current.Web.EnsureUser(strUserName);
       if (objSPUser != null)
      {
         userCollection.Add(new SPFieldUserValue(SPContext.Current.Web, objSPUser.ID, objSPUser.Name));
       }
    }
  if (userCollection.Count > 0)
  item[field.ColumnName] = userCollection;
  item.Update();
 }
}


public string[] StringToArray(string input, string separator)
{
string[] stringList = input.Split(separator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
return stringList;
}

Thanks