1

I want to restrict users from accessing a list. I have a custom webpart that accesses that list. But if I restrict the access, the code also cannot access it and throws exception.

So is there any way out so that user cannot access the list through browser but the Webpart accessed by the user can?

Ankita Sen
  • 434
  • 5
  • 11

1 Answers1

1

Yes, the best way is to open the containing site-collection with the system account:

SPWeb ctxWeb = SPContext.Current.Web;
using (SPSite adminSite= new SPSite(ctxWeb.Site.ID, SPUserToken.SystemAccount))
{  
  using (SPWeb adminWeb = adminSite.OpenWeb(ctxWeb.ID))
  {
    SPList adminList = adminWeb.Lists["TheRestrictedList"]; 
  } 
}

Every object retrieved from a site collection opened with a certain user token behaves as the given user is directly accessing the element.

Since we are opening the SPSite with the system account token, we have full control on the objects regardless the logged-in user.

Stefan
  • 14,530
  • 4
  • 55
  • 62
  • 1
    SPUserToken.SystemAccount is used in Sharepoint 2010 and I am using sharepoint 2007. I have already tried with: '**SPSecurity.RunWithElevatedPrivileges(delegate() {---code---});**' – Ankita Sen Jun 12 '12 at 13:06
  • For SP 2007, replace SPUserToken.SystemAccount with ctxWeb.Site.SystemAccount.UserToken. [SPSite.SystemAccount](http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsite.systemaccount(v=office.12).aspx) is available in SP 2007. – Rich Bennema Jun 14 '12 at 20:11