Guest User

Untitled

a guest
May 25th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. <%@ Page language="VJ#" %>
  2. <%@ Import Namespace="System.Web" %>
  3. <%@ Import Namespace="System.Web.Security" %>
  4. <%@ Import Namespace="System.Security.Principal" %>
  5. <%@ Import Namespace="System.Runtime.InteropServices" %>
  6.  
  7. <script runat=server>
  8. public static int LOGON32_LOGON_INTERACTIVE = 2;
  9. public static int LOGON32_PROVIDER_DEFAULT = 0;
  10.  
  11. WindowsImpersonationContext impersonationContext;
  12.  
  13. /** @attribute DllImport("advapi32.dll") */
  14. public static native int LogonUserA(String lpszUserName,
  15. String lpszDomain,
  16. String lpszPassword,
  17. int dwLogonType,
  18. int dwLogonProvider,
  19. System.IntPtr[] phToken);
  20.  
  21. /** @attribute DllImport("advapi32.dll",
  22. CharSet=CharSet.Auto, SetLastError=true) */
  23. public static native int DuplicateToken(System.IntPtr hToken,
  24. int impersonationLevel,
  25. System.IntPtr[] hNewToken);
  26.  
  27. /** @attribute DllImport("kernel32.dll",CharSet=CharSet.Auto) */
  28. public static native boolean CloseHandle(System.IntPtr[] handle);
  29.  
  30.  
  31. /** @attribute DllImport("advapi32.dll",
  32. CharSet=CharSet.Auto,SetLastError=true) */
  33. public static native boolean RevertToSelf();
  34.  
  35. public void Page_Load(Object s, System.EventArgs e)
  36. {
  37. if(impersonateValidUser("username", "domain", " password"))
  38. {
  39. //Insert your code that runs under the security context of a specific user here.
  40. undoImpersonation();
  41. }
  42. else
  43. {
  44. //Your impersonation failed. Therefore, include a fail-safe mechanism here.
  45. }
  46. }
  47.  
  48. private boolean impersonateValidUser(String userName, String domain, String password)
  49. {
  50. WindowsIdentity tempWindowsIdentity;
  51. System.IntPtr[] token = new System.IntPtr[1];
  52. System.IntPtr[] tokenDuplicate = new System.IntPtr[1];
  53.  
  54. if(RevertToSelf())
  55. {
  56. if(LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
  57. LOGON32_PROVIDER_DEFAULT, token) != 0)
  58. {
  59. if(DuplicateToken(token[0], 2, tokenDuplicate) != 0)
  60. {
  61. tempWindowsIdentity = new WindowsIdentity(tokenDuplicate[0]);
  62. impersonationContext = tempWindowsIdentity.Impersonate();
  63. if (impersonationContext != null)
  64. {
  65. CloseHandle(tokenDuplicate);
  66. CloseHandle(token);
  67. return true;
  68. }
  69. }
  70. }
  71. }
  72. if(!token[0].Equals(System.IntPtr.Zero))
  73. CloseHandle(token);
  74. if(!tokenDuplicate[0].Equals(System.IntPtr.Zero))
  75. CloseHandle(tokenDuplicate);
  76. return false;
  77.  
  78. }
  79.  
  80. private void undoImpersonation()
  81. {
  82. impersonationContext.Undo();
  83. }
Add Comment
Please, Sign In to add comment