Thursday 30 January 2014

Authentication, authorization, and security in SharePoint

Authentication and Authorization in Share Point
Authentication is process of challenging and approving user’s Identity, while Authorization comes after the authentication, where user based permissions, rights, and privileges are taken into account. Microsoft SharePoint Services 3.0, MOSS, and SharePoint Foundation supports security for user access at the Web site, list, library folder, and item levels2. This security is managed based on role based mechanisms where each user is able to perform specific operation and all levels based on his/her role, and this is achieved through Authorization process once the user is successfully authenticated by the underlying authentication mechanism.

Thursday 16 January 2014

RunWithElevatedPrivileges

Execute Code In SharePoint With Elevated Privileges

How To Run Code In SharePoint That Usually Can’t Be Executed With The Current Users Credentials.

Ever needed to execute a block of code in SharePoint that would normally fail or throw an exception because of the level of permissions the currently logged in user has?
If so, here is a quick way to achieving the results you desire..
Quite simply we will,
  1. Create a delegate method that will run with elevated permissions
  2. We will wrap this new delegate method with the SPSecurity.RunWithElevatedPrivileges() block
    • Which will in turn execute the specified method with Full Control rights even if the user does not otherwise have Full Control
  3. Provide a simple example of how to implement this in your solution such as an event receiver.
Limitations to take note of,
  1. The RunWithElevatedPrivileges method can not be used within a sandbox solution
    • Generally speaking no form of user impersonation can be done in a sandbox solution
  2. The item that is actioned with elevated privileges will be executed under the web applications App pool account in IIS, which means that the modified user of the document/list item will most likely display asSYSTEM ACCOUNT
    • Though it is possible to change with programmatically in the listitems metadata, however for the purpose of this post it will be omitted.
  3. If you did not want to execute the code as the App Pool account for any reason, you could alternatively use a specific user account to execute the code under by implementing the SPUserToken class

Show me the code!

To help give you a ‘bigger picture’ idea of how to implement this type of code, in the below example I will show you how to,
  1. Create a simple SharePoint Event Receiver
  2. Check if the logged in user has the required level of permissions to do a certain action such as MoveTo(this will change the URL of the uploaded file)
  3. If the user does not have the required permissions we will execute the RunWithElevatedPrivileges method that we will create.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
 
namespace SharePoint.Development.EventReceivers
{
    ///
    /// List Item Events
    ///
    public class ItemCheckedInEventReceiver : SPItemEventReceiver
    {
        public override void ItemCheckedIn(SPItemEventProperties properties)
        {
            base.EventFiringEnabled = false; // Disable event receiver firing so that we do not accidentally kick off a different thread
            try
            {
                // Check if user has a certain set of permissions, i.e. can they delete items? if not, then we will have to RunWithElevatedPrevileges
                if (properties.Web.DoesUserHavePermissions(properties.UserLoginName, SPBasePermissions.DeleteListItems))
                {
                    SPFile file = properties.ListItem.File;  // Get the file
                    file.MoveTo(newURL);             // Move it to the new location
                }
                else
                {
                    string newURL = "http://newfilelocation/document.doc";
                    RunWithElevatedPrivileges(properties, newURL); // User doesn't have required permissions and therefore the code must be executed with Elevated perms.
                }
            }
            catch (Exception ex)
            {
                // Write to ULS and Event Logs
            }
            finally
            {
                base.EventFiringEnabled = true;
            }
        }
        public static void RunWithElevatedPrivileges(SPItemEventProperties properties, string newURL)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    // Everything executed here will be executed under the AppPool account and will have full permissions.. so becareful!!
                    using (SPSite site = new SPSite(properties.SiteId))
                    {
                        using (SPWeb web = site.OpenWeb(properties.Web.ID))
                        {
                            SPList list = web.Lists[properties.ListId];
                            SPListItem listItem = list.Items.GetItemById(properties.ListItemId);
                            SPFile file = listItem.File;
                            file.MoveTo(newURL);
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                // Write to ULS and Event Logs
            }
        }
   }