Win32 API Documentation

Microsoft Windows SDK

EndImpersonation Function

SecurityBaseAPI

The EndImpersonation function restores the calling thread's original security context.

Syntax

BOOL EndImpersonation(
  VOID
);

Parameters

This function takes no parameters.

Return value

If the function succeeds, the return value is a nonzero value. If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The EndImpersonation function ends the impersonation of a client by the server thread. The server thread's security context is restored to what it was before the ImpersonateLoggedOnUser or ImpersonateNamedPipeClient function was called.

A server application must call EndImpersonation after it has finished using the client's security token. Failure to do so can lead to security vulnerabilities.

To obtain a client's security token to impersonate, a server application can use the GetThreadId function to get the client process ID, and then OpenProcessToken to get the client's token.

It is important to note that the thread that calls EndImpersonation must be the same thread that called the impersonation function (e.g., ImpersonateLoggedOnUser).

Requirements

Component Value
Minimum supported client Windows XP
Minimum supported server Windows Server 2003
Target Platform Windows
Header securitybaseapi.h (include windows.h)
Library Advapi32.lib
DLL Advapi32.dll

See also

Example

The following C++ code snippet demonstrates how to use EndImpersonation:


#include <windows.h>
#include <iostream>

// Assume hClientToken is a valid handle to a client's access token
// obtained from ImpersonateLoggedOnUser or similar.

HANDLE hClientToken = /* ... get token handle ... */;
BOOL impersonated = FALSE;

if (hClientToken != NULL) {
    impersonated = ImpersonateLoggedOnUser(hClientToken);

    if (impersonated) {
        std::cout << "Successfully impersonating client." << std::endl;

        // Perform operations using the client's security context...

        // Restore the original security context
        if (EndImpersonation()) {
            std::cout << "Successfully ended impersonation." << std::endl;
        } else {
            std::cerr << "Failed to end impersonation. Error: " << GetLastError() << std::endl;
        }
    } else {
        std::cerr << "Failed to impersonate client. Error: " << GetLastError() << std::endl;
    }
    CloseHandle(hClientToken); // Close the token handle if it was opened by this thread
}