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.