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

2 Answers 2

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 + ")";
2
  • 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
    Commented Feb 10, 2014 at 7:59
  • The problem solved when You add the user to the site under site setting -> people and groups.
    – Medes
    Commented Feb 10, 2014 at 8:09
0

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

2
  • So that means the user never logged into the site and thus the UserInfoList didn't had any information about this user :) Commented Feb 10, 2014 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
    Commented Feb 11, 2014 at 8:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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