Impersonate e DuplicateToken

Stavo facendo dei test sull’Impersonate e confrontando alcuni esempi (quello trovato sul libro di Balena versione 2003 e quello trovato su MSDN http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemSecurityPrincipalWindowsIdentityClassImpersonateTopic2.asp) mi è balzata all’occhio una differenza ovvero l’uso della funzione DuplicateToken.
L’esempio di MSDN ne faceva uso mentre quello riportato sul libro di balena no.

La spiegazione sta in questo articolo:
PRB: “Unable to Impersonate User” Error Message When You Use WindowsIdentity.Impersonate Method
http://support.microsoft.com/default.aspx?scid=KB;EN-US;319615

SYMPTOMS
When you use the System.Security.Principal.WindowsIdentity.Impersonate method, you may receive the following error message:
Unable to impersonate user.

CAUSE
This problem occurs because of the type of token that is used when the WindowsIdentity object is created. You receive the error message that is listed in the “Symptoms” section if the token is not a primary token when you try to impersonate. You must have an impersonation token for the WindowsIdentity.Impersonate method to work.

RESOLUTION
To obtain a primary token from an impersonation token, use the DuplicateToken Win32 function.

STATUS
This bug was corrected in Microsoft .NET Framework Class Libraries 1.1.

Quindi con il Framework 1.1 non è più necessario invocare la DuplicateToken e visto che il libro di Balena versione 2003 fa riferimento appunto alla versione 1.1 giustamente non utilizza DuplicateToken per implementare Impersonate.