2

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 + ")";
         }
    }
});
1

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 + ")";
  • Thanks for your answer Arsalan, I tested your suggestion but I got same error. I think maybe I get this error because the web application is an Extranet and used FBA to authenticate users, when you go to Site Settings --> people and groups you cannot find any user there but when you retrieve users using web.AllUsers it returns all users that exists in FBA database and has access to the site. – Medes Feb 10 '14 at 7:59
  • The problem solved when You add the user to the site under site setting -> people and groups. – Medes Feb 10 '14 at 8:09
0

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

  • So that means the user never logged into the site and thus the UserInfoList didn't had any information about this user :) – Arsalan Adam Khatri Feb 10 '14 at 8:16
  • The user was already logged into the several times but he was not member of any group. the web application uses Form based Authentication. – Medes Feb 11 '14 at 8:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.