Impersonate user programmatically on Sharepoint 2013 (C#)

5.5k Views Asked by At

This might an odd question, but what I would like to achieve is a functionality that would allow specific users to view SharePoint pages as if they were logged in as different users.

Let's say we have a Student page and a Staff page. I am not a student, but I would like to log in as one to be able to view the Student page as a student would. Does that make sense? So, in a way, impersonation.

I have found some impersonation code, and it works fine, but it is not what I want. I was able to impersonate a user in a separate SPWeb object. But, how do I change the current user context of the active SPWeb object?

Here's what I've got:

private void ImpersonateUser()
    {
        string siteURL = "http://mywebsite/";
        SPSite parentSite = new SPSite(siteURL);
        SPUserToken systemToken = parentSite.SystemAccount.UserToken;
        using (SPSite site = new SPSite(siteURL, systemToken))
        {
            using (SPWeb web = site.OpenWeb())
            {
                web.AllowUnsafeUpdates = true;
                OpenUserContext(web, siteURL, @"domain\studentuser");
            }
        }
    }

    private void OpenUserContext(SPWeb web, string siteURL, string user)
    {
        try
        {
            SPUser ensure = web.EnsureUser(user);
            SPSite impSite = new SPSite(siteURL, ensure.UserToken);
            SPWeb impWeb = impSite.OpenWeb();

            // Do something as impersonated user
            label1.Text = "Currently logged in as: " + impWeb.CurrentUser.ToString() + "(" + impWeb.CurrentUser.Name + ")";

        }
        catch (Exception ex) { label1.Text = ex.Message + "<br>" + user; }
    }

Thanks a lot.

2

There are 2 best solutions below

4
On

While SharePoint does allow your code to interact with it while impersonating a user, it has no support to allow you to browse and view things as if you were another user.

You can, however, code your customizations to take in to account your desire and add the impersonation logic to them (but that's up to you to implement and SP will not help you there). Project Server does something like what you are asking but only when it comes to Project Server owned elements.

0
On

If your impersonation code is executing behind a custom .aspx page in SharePoint, you can programmatically add an xsltlistviewwebpart to the page to display one or more list views under your impersonated context.