I'm trying to execute a search query while impersonating a specific user.
The goal is to have a web service that receives the user login name (via querystring or request header), perform a full text query and give back the results, respecting the security trimming.
Putting it differently I need to get only the results the impersonated user is entitled to see.
My current code is:
var spUser = SPContext.Current.Web.EnsureUser(loginName);
HttpRequest request = new HttpRequest("", SPContext.Current.Web.Url, "");
var web = SPContext.Current.Web;
HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter(CultureInfo.CurrentCulture)));
if (HttpContext.Current.Items.Contains("HttpHandlerSPWeb"))
{
HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
}
else
{
HttpContext.Current.Items.Add("HttpHandlerSPWeb", web);
}
WindowsIdentity identity = WindowsIdentity.GetCurrent();
typeof(WindowsIdentity).GetField("m_name", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(identity, spUser.LoginName);
HttpContext.Current.User = new GenericPrincipal(identity, new string[0]);
identity.Impersonate();
//execute query here
Basically I'm replacing the current identity before instantiating the FullTextQuery, but it's the same as doing nothing, as the results will only change according to the real logged user, and not the one impersonated.
Any hints here?
Thanks in advance, Cheers !
I was able to get it to work by doing impersonation when running with elevated priveleges. see my post here: http://vishalseth.com/post/2013/11/05/Impersonated-Searching-against-SharePoint.aspx