特定のユーザーになりすまして、そのユーザーが表示する検索結果をすべてのユーザーに返す方法の例を次に示します。言うまでもなく、これはもちろんセキュリティ上のリスクであるため、注意して使用してください。
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System.Security.Principal;
using Microsoft.Office.Server.Search.Administration;
using Microsoft.Office.Server.Search.Query;
using Microsoft.SharePoint.Administration;
namespace SharePointSearchImpersonation.WebPart1
{
[ToolboxItemAttribute(false)]
public class QuerySearchImpersonatedWebPart : WebPart
{
protected override void CreateChildControls()
{
try
{
// Run elevated since the user, the apppool account, that impersonate other users needs the following
// local policies (run secpol.msc): "Impersonate a client after authentication" & "Act as part of the operating system"
// The apppool account must be granted above rights.
SPSecurity.RunWithElevatedPrivileges(
delegate
{
// Setup the windows identity to impersonate the search as.
WindowsIdentity identity = new WindowsIdentity("user3@dev.local");
// Create a new ImpersonationContext for the identity
using (WindowsImpersonationContext wic = identity.Impersonate())
{
SearchQueryAndSiteSettingsServiceProxy settingsProxy = SPFarm.Local.ServiceProxies.GetValue<SearchQueryAndSiteSettingsServiceProxy>();
// Get the search proxy by service application name
SearchServiceApplicationProxy searchProxy = settingsProxy.ApplicationProxies.GetValue<SearchServiceApplicationProxy>("Search Service Application");
KeywordQuery query = new KeywordQuery(searchProxy);
query.ResultTypes = ResultType.RelevantResults;
query.QueryText = "test";
query.RowLimit = 25;
ResultTableCollection result = query.Execute();
DataTable dt = new DataTable();
dt.Load(result[ResultType.RelevantResults]);
GridView gv = new GridView();
Controls.Add(gv);
gv.AutoGenerateColumns = true;
gv.DataSource = dt;
gv.DataBind();
}
});
}
catch (Exception ex)
{
Controls.Add(new LiteralControl() {Text = ex.ToString()});
}
}
}
}