Archive for the ‘ Security ’ Category

SharePoint Run with Elevated Privileges Best Practices

Running code in SharePoint with elevated privileges can be risky. It’s always important to make sure you’re using it appropriately. I did a quick Google search and found a great list best practices when using it. You can find the list Here.

The post offers a great alternative to running with elevated privileges. Instead, impersonate the SHAREPOINT\system account and use it to instantiate new SPSite and SPWeb objects. Check out the code below. (Courtesy of Soumya Dasari)

 var user = SPContext.Current.Web.AllUsers[@"SHAREPOINT\SYSTEM"];
 var superToken = user.UserToken;
 using (var site = new SPSite(SPContext.Current.Web.Url, superToken))
 {
    // This code runs under the security context of the SHAREPOINT\system
 // for all objects accessed through the "site" reference. Note that it's a
 // different reference than SPContext.Current.Site.
    using(var elevatedWeb = site.OpenWeb())
    {
       // Perform actions as SYSTEM here
    }
 }
Advertisements

SPMetal with Anonymous Access

So, I recently ran into a problem with using SPMetal with anonymous access. When Anonymous users access a web part that runs LINQ queries, they’ll get prompted for credentials in SharePoint 2010. The problem is actually related to the way the LINQ code works. It uses the default SPContext.Current to get the site objects. This becomes a problem when you need to run a piece of code with elevated permissions because without rebuilding the SPContext.Current, you’re still using the default permissions. With the default permissions, as an anonymous user, you will not have enough access to make calls using LINQ and as a result, you’ll be prompted to log in.

This blog had an okay solution:

Use the HttpContext object to force all SP objects to be created again. When this happens within the RunWithElevatedPrivileges method, the SPContext is recreated with this higher level of priveleges.

This code has its problems though.

Continue reading

Conditionally Hiding the Ribbon Based on User Permissions

So, I recently needed to hide the SharePoint 2010 ribbon. After trying several different options, I found a very simple, but solid, solution.

To start you’ll need to crack open your master page in SharePoint designer.

Next, find the¬†<div id=”s4-ribbonrow” class=”s4-pr s4-ribbonrowhidetitle”>¬†tag that should be just a few lines below the head tag on the standard SharePoint 2010 V4 master.

Now, you’ll want to add a SPSecurityTrimmedControl to the page like the one below.

Continue reading