2 // System.Security.Principal.WindowsImpersonationContext
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 // Sebastien Pouliot (sebastien@ximian.com)
8 // (C) 2002 Ximian, Inc (http://www.ximian.com)
9 // (C) 2004 Novell (http://www.novell.com)
13 using System.Runtime.CompilerServices;
14 using System.Security;
16 namespace System.Security.Principal {
18 public class WindowsImpersonationContext {
20 private IntPtr _token;
23 internal WindowsImpersonationContext (IntPtr token)
25 // we get a copy to control it's lifetime
26 _token = DuplicateToken (token);
27 if (!SetCurrentToken (token)) {
28 throw new SecurityException ("Couldn't impersonate token.");
33 ~WindowsImpersonationContext ()
42 if (!RevertToSelf ()) {
44 throw new SecurityException ("Couldn't switch back to original token.");
48 GC.SuppressFinalize (this);
51 // see mono/mono/metadata/security.c for implementation
53 [MethodImplAttribute (MethodImplOptions.InternalCall)]
54 private extern static bool CloseToken (IntPtr token);
56 [MethodImplAttribute (MethodImplOptions.InternalCall)]
57 private extern static IntPtr DuplicateToken (IntPtr token);
59 [MethodImplAttribute (MethodImplOptions.InternalCall)]
60 private extern static bool SetCurrentToken (IntPtr token);
62 [MethodImplAttribute (MethodImplOptions.InternalCall)]
63 private extern static bool RevertToSelf ();