RunWithElevatedPriviliges and UserProfile

"RunWithElevated() does an ImpersonateSelf(), so the thread is impersonating the process identity. Also, all SPSite objects created within the RunWithElevated() scope are treated as SHAREPOINT\system, have full control over the site.

But it does not change HttpContext.Current.User. so if the original user was anonymous, the HttpContext.Current.User is still anonymous. If some code explicitly check against HttpContext, you may still get access denied."

 

So, in summary, you impersonate the process identity (i.e., your app pool RunAs account) and you get sharepoint\System permissions in your app pool.

 

Additional info that I have uncovered over time:

 

wrt Elevated Code in general:

You should never try to access objects via SPContext.Current (i.e., SPContext.Current.[Site | Web] within elevated code; instead, pass either the SiteID/WebID to the elevated code and "new" the SPSite or SPWeb as needed.

 

wrt Creating User Profiles:

so if you are writing UserProfile creation code that runs in your MOSS web app, you need to grant the AppPool RunAs account appropriate access on the SSP.

Even if you do this, your code may still not work if the original user was not authenticated (anonymous).

Additional information from my friend Ron who works with me

You cannot create a User Profile from the current HttpRequest when the current user is anonymous, even if you properly run with elevated privleges (using all of the best practices for ensuring that you open the resources from within the elevated context).

The current user must be authenticated in order to create a user profile.

The devil is in the details, but it involves the fact that the HttpRequest is still marked as anonymous.

In our case, the anon-user fills out a "registration form" and hits submit. At that point, we create a user in the membership provider, call FormsAuth to force authentication, set a session state flag, and then re-direct to ourselves. The re-direct causes the forced-auth to take effect on the new incoming http request. At that point, the page sees the flag and knows that it needs to "complete" the registration process. At this point, the user is no longer anonymous and we can now use the Elevated Privs delgate to create the user profile.

Make sure that your web app pool account has the necessary rights (i.e., manage user profiles) on the SSP.

Comments

  • Anonymous
    June 15, 2008
    PingBack from http://stevepietrek.com/2008/06/15/links-6152008/

  • Anonymous
    September 03, 2008
    Many thanks for the clarification on elevated code and the context object.  You saved my hair! The context is an odd bird isn't it?