Wednesday, December 2, 2009

SharePoint Elevated Privileges and SPUserToken FBA

These two lines of code when working with the SharePoint object Model will allow you to see what user or security context if you like your is running under.

You will need to reference the correct libraries in your .NET classes use statement however the intellisense will pick this up for you.

WindowsPrincipal principal = GetWindowsIdentityPrincipalObject();
SPUserToken spToken = spWeb.CurrentUser.UserToken; 
 
(spWeb is a variable already created code left out)
 
SPSecurity.RunWithElevatedPrivileges(delegate()
{
          //code you want to run
});
 
This will allow you to run code with the permission level of the app pool account the particular site collection is running in.
 
Without giving this account ridiculously high Privileges which is not a good idea this will not necessarilly allow you to do certain things.
 
For example if you want to give users with Contribute rights the ability to create users in an FBA Extranet implementation run with elevated privilleges will not do it.
 
What I did to make this work is create a base page that the FBA applications pages inherit from with a couple of properties
 
protected SPUserToken _userToken;
protected SPUserToken UserToken
{
get
{
if (_userToken != null)
{
return _userToken;
}
_userToken = SPContext.Current.Web.AllUsers[Account].UserToken;
return _userToken;
}
}

In the above piece of code the Account string is read from an xml config file and has a Windows account with sufficient rights in SharePoint land to create FBA Users.

protected SPSite _site;
protected SPSite CurrSite
{
get
{
if (_site != null)
{
return _site;
}
_site = new SPSite(SPContext.Current.Site.Url, UserToken);
return _site;
}
}
 
Apart from this what other pearls do I have regarding security quite a few I am no expert in this area as it is complicated and there are  a number of good postings on the web. What I do recommend though is creating special accounts for special puposes with the correct permission levels and a description of what the account does (appropriately named may also be a help). If you are using kerberos this should include its Kerberos set up this should also be documented else where.
 
I have seen some embarrasing situations where people forget what accounts they have set up or a previous administrator did not document it and discovering things that should be well known to keep your SP farm operating properly is a waste of time.
 
On FBA application pages and application pages in general there are a number of other good postings on the web which you will need to read.

No comments:

Post a Comment