I’m trying to call a windows api (that only seems to work in logged on user’s context) from a windows service (running as SYSTEM). I’m able to get the token for logged on user. I don’t get any errors when I call ImpersonateLoggedOnUser(), it returns true. But the DoSomethingInUserContext() still executes in the SYSTEM context. What am I doing wrong?
DWORD sessionIdDw = WTSGetActiveConsoleSessionId();
HANDLE hToken;
if (!WTSQueryUserToken(sessionIdDw, &hToken))
LOG() << "WTSQueryUserToken failed: " << GetLastError();
HANDLE hDuplicated = NULL;
if (!DuplicateTokenEx(hToken, TOKEN_ALL_ACCESS, NULL, SecurityImpersonation, TokenImpersonation, &hDuplicated)) {
LOG() << "DuplicateTokenEx failed: " <<GetLastError();
}
if (!ImpersonateLoggedOnUser(hDuplicated)) {
LOG() << "ImpersonateLoggedOnUser failed " << GetLastError();
}
else {
DoSomethingInUserContext();
if (!RevertToSelf()) {
LOG() << "RevertToSelf failed" << GetLastError();
}
}
CloseHandle(hDuplicated);
CloseHandle(hToken);