Tell me more ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I want to issue a search query from code using KeywordQuery as a specific user. The background is that item level security needs to be applied. I want security trimmed search results.

I tried two things so far:

  1. creating KeywordQuery with SPSite that has been created using a user token
  2. executing query as impersonated user

Both approaches failed. The first one gives me all search results and seems to ignore the user I created the SPSite with.

The second approach looks like this:

var impersonatedIdentity = new WindowsIdentity("user@domain");
var wic = impersonatedIdentity.Impersonate();
[ query here ]
wic.Undo();

It gives an error: System.Data.SqlClient.SqlException : A transport-level error has occurred when sending the request to the server. (provider: Shared Memory Provider, error: 0 - Either a required impersonation level was not provided, or the provided impersonation level is invalid.).

I found a quote from Corey Roth here, saying:

The KeywordQuery class uses the credentials of the current user. The documents you see will be security trimmed down to the specific user.

This sounds like my second approach. But it doesn't work.

Does anybody know how to query for search results as specific user?

share|improve this question

1 Answer

I found the solution. Impersonating the user the way I did it was not enough. You actually have to log in or get the token of an already logged in user.

Example for logging in:

IntPtr token = IntPtr.Zero;
LogonUser("user@domain", null, "password", LogonSessionType.Network, LogonProvider.Default, out token);
var impersonatedIdentity = new WindowsIdentity(token);
var wic = impersonatedIdentity.Impersonate();

[ query here ]

wic.Undo();
CloseHandle(token);

(Inspiration taken from this blog post showing different ways to impersonate. You can also find the imports of LogonUser and CloseHandle there as well as the used enums.)

The SqlException is gone and the search results are security trimmed for the impersonated user.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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