Question

I am using following code to impersonate a user on an extranet which uses Form Based Authentication, however when it comes to this line (SPSite s = new SPSite(siteStr, userToken);) it throws

InvalidOperationException.

I have tested and know that allUSers[4] exists.

string siteStr = "http://mywebSiteUrl/";

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(siteStr))
    {
        using (SPWeb web = site.OpenWeb())
        {
             SPUserToken userToken = web.AllUsers[4].UserToken;

             SPSite s = new SPSite(siteStr, userToken);

             SPWeb w = s.OpenWeb();

             myLiteral.Text = "Currently logged in as: " + w.CurrentUser.ToString() + "( " + w.CurrentUser.Name + ")";
         }
    }
});
Was it helpful?

Solution 2

The problem solved when You add the user to the site under site setting -> people and groups

OTHER TIPS

Can you try following, I have just kept new SPSite and SPWeb object outside RunWithElevatedPrivileges

string siteStr = "http://mywebSiteUrl/";
SPUserToken userToken;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
  using (SPSite site = new SPSite(siteStr))
  {
    using (SPWeb web = site.OpenWeb())
    {
         userToken = web.AllUsers[4].UserToken;
     }
   }
});

SPSite s = new SPSite(siteStr, userToken);

SPWeb w = s.OpenWeb();

myLiteral.Text = "Currently logged in as: " + w.CurrentUser.ToString() + "( " + w.CurrentUser.Name + ")";
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top