⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 authentication.cs

📁 JAVA实现的RSA公钥加密方法
💻 CS
字号:
using System;
using System.DirectoryServices;
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Specialized;
using Microsoft.VisualBasic;
using System.Security.Principal;
using System.Threading;

namespace DJD.Security
{

	/// <summary>
	/// Integrates with ActiveDirectory Servers for purpose of authentication. Developed by Dom DiNatale 11/15/02
	/// </summary>
	[Guid("4AC6FEAF-42EC-4c35-A21E-DE3820171626"), ClassInterface(ClassInterfaceType.AutoDual)]
	public class Authentication : IDisposable
	{
		[DllImport("advapi32.dll", SetLastError=true)]
		private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, 
			int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

		[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
		private extern static bool CloseHandle(IntPtr handle);

		[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
		private extern static bool DuplicateToken(IntPtr ExistingTokenHandle, 
			int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);



		#region Enums
		public enum AuthenticationTypes
		{
			ActiveDirectory,
			LDAP
		}
		#endregion

		#region Declarations
		private string _path = "";
		private System.Collections.SortedList _usrPropsDict;
		private AuthenticationTypes _authtype = AuthenticationTypes.ActiveDirectory;
		#endregion

		#region Properties
		/// <summary>
		/// Provides every domain name available on the network.
		/// </summary>
		public System.Collections.SortedList Domains
		{
			get
			{
				return GetDomains();
			}

		}
		public AuthenticationTypes AuthType
		{
			get
			{
				return _authtype;
			}
			set
			{
				_authtype = value;
			}

		}

		/// <summary>
		/// Provides every domain name available on the network.
		/// </summary>
		public string[] DomainsStr
		{
			
			get
			{
				SortedList sl = GetDomains();
				string[] m_array = new string [sl.Count];
				
				for (int i = 0; i <= sl.Count-1; i++)
				{
					m_array[i] = sl.GetKey(i).ToString();
				}
				return m_array;
			}

		}
		/// <summary>
		/// Provides the ActiveDirectory path currently being used.
		/// </summary>
		public string Path
		{
			get
			{
				return _path;
			}
		}

		/// <summary>
		/// Provides all of the properties for the current user in a ListDictionary format.
		/// </summary>
		public System.Collections.SortedList Properties
		{
			get
			{
				return _usrPropsDict;
			}

		}

		#endregion

		#region Public Methods
		/// <summary>
		/// Starts a new instance of this class.
		/// </summary>
		public Authentication()
		{
		}
	
		/// <summary>
		/// Authenticates a user in the specified domain against ActiveDirectory Server(s).
		/// </summary>
		/// <param name="domain">The domain the account is to be authenticated in.</param>
		/// <param name="UserID">The Windows NT UserID.</param>
		/// <param name="password">The password for the UserID.</param>
		/// <returns>Returns a string: "True" if successful, or exception message if unsuccessful.</returns>
		public string Authenticate(string domain, string userID, string password)
		{
			string domainAndUsername = domain + "\\" + userID;
			string retVal;
			switch (_authtype)
			{
				case Authentication.AuthenticationTypes.ActiveDirectory:
					_path = "WinNT://" + domain;
					break;
				case Authentication.AuthenticationTypes.LDAP:
					_path = "LDAP://" + domain;
					break;
			}
			DirectoryEntry entry;
			try
			{	
				entry = new DirectoryEntry(_path, domainAndUsername, password, System.DirectoryServices.AuthenticationTypes.ReadonlyServer);
						
				object obj = entry.NativeObject; /// makes sure the object is bound.
				_path = entry.Path;
				retVal = "True";
				obj = null;
				entry.Close();
				entry.Dispose();
				entry = null;
				GC.Collect();

				//Resolve(domain,userID,domain,userID,password);
			}
			catch(Exception ex)
			{
				retVal = ex.Message;
			}
			finally
			{
				
				GC.Collect();
			}
			return retVal;
		}

		/// <summary>
		/// Allows you to change the password of a user.
		/// </summary>
		/// <param name="domain">The domain the use is in.</param>
		/// <param name="userID">The users' id</param>
		/// <param name="oldPassword">The current password.</param>
		/// <param name="newPassword">The new password.</param>
		/// <returns>True if successful, False if not.</returns>
		public bool ChangePassword(string domain, string userID, string oldPassword, string newPassword)
		{
			string result = "";
			return ChangePassword(domain,userID,oldPassword,newPassword,ref result);
		}
		
		/// <summary>
		/// Allows you to change the password of a user.
		/// </summary>
		/// <param name="domain">The domain the use is in.</param>
		/// <param name="userID">The users' id</param>
		/// <param name="oldPassword">The current password.</param>
		/// <param name="newPassword">The new password.</param>
		/// <param name="result">error message if there is one</param>
		/// <returns>True if successful, False if not.</returns>
		public bool ChangePassword(string domain, string userID, string oldPassword, string newPassword, ref string result)
		{
			// *** IMPORTANT INFORMATION *** //
			// When you call a function like this, the credentials from the earliest caller are used to contact Active
			// Directory. For example. If you were to use this in a web application, the application serving the web server 
			// would have to be running under an account that has access to AD. (Win2K: inetinfo.exe, Win2K3 (IIS6): w3wp.exe)
			// In IIS 6, you can set this at the application pool level. Note that the user you provide needs the same
			// access as the NETWORK SERVICE account (check local and group policies). 
			// There is an attempted workaround for this restriction in the catch statement below (commented out). 
			// This approach will not work in a web application, you'll get an error about not being able to impersonate.
			// It may work, however in a win application. 

			string domainAndUsername = domain + "\\" + userID;
			switch (_authtype)
			{
				case Authentication.AuthenticationTypes.ActiveDirectory:
					_path = "WinNT://" + domain;
					break;
				case Authentication.AuthenticationTypes.LDAP:
					_path = "LDAP://" + domain;
					break;
			}
			try
			{	
				DirectoryEntry ent = new DirectoryEntry();
				ent.Username = domain + "/" + domain + "\\" + userID;
				ent.Password = oldPassword;
				ent.AuthenticationType = System.DirectoryServices.AuthenticationTypes.Secure;
			
				object obj1 = ent.NativeObject; /// makes sure the object is bound.
				
				DirectorySearcher Searcher = new DirectorySearcher(ent,"(sAMAccountName=" + userID + ")");
				Searcher.SearchScope = SearchScope.Subtree;
				SearchResult sResult = Searcher.FindOne();

				_path = sResult.GetDirectoryEntry().Path;
				
				ent = sResult.GetDirectoryEntry();
				ent.Invoke("ChangePassword", new object[] {oldPassword, newPassword});
				ent.CommitChanges();
				return true;		
			}
			catch(Exception ex)
			{
				// This hasn't been tested very well, so use it at your own risk... it should work though!
				//http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemsecurityprincipalwindowsidentityclassimpersonatetopic2.asp
//////				try //attempt to impersonate the user that is trying to logon rather than using the 
//////					// credentials of the person calling this function.
//////				{
//////					const int LOGON32_PROVIDER_DEFAULT = 0;
//////					const int LOGON32_LOGON_INTERACTIVE = 2;					//This parameter causes LogonUser to create a primary token.
//////					const int SecurityImpersonation = 2;
//////
//////					Console.WriteLine("Before impersonation: " + WindowsIdentity.GetCurrent().Name);
//////
//////					IntPtr tokenHandle = new IntPtr(0);
//////					IntPtr dupeTokenHandle = new IntPtr(0);
//////					//try to logon the user
//////					bool returnValue = LogonUser(userID,domain,oldPassword,LOGON32_LOGON_INTERACTIVE,LOGON32_PROVIDER_DEFAULT, ref tokenHandle);
//////					if (returnValue == true) 
//////					{
//////						bool retVal = DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle);
//////						if (retVal)
//////						{
//////							WindowsIdentity newId = new WindowsIdentity(dupeTokenHandle);
//////							WindowsImpersonationContext impersonatedUser = newId.Impersonate();
//////							Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name);
//////
//////							// COPIED FROM ABOVE TO CHANGE PASSWORD
//////							DirectoryEntry ent = new DirectoryEntry();
//////							ent.Username = domain + "/" + domain + "\\" + userID;
//////							ent.Password = oldPassword;
//////							ent.AuthenticationType = System.DirectoryServices.AuthenticationTypes.Secure;
//////			
//////							object obj1 = ent.NativeObject; /// makes sure the object is bound.
//////				
//////							DirectorySearcher Searcher = new DirectorySearcher(ent,"(sAMAccountName=" + userID + ")");
//////							Searcher.SearchScope = SearchScope.Subtree;
//////							SearchResult sResult = Searcher.FindOne();
//////
//////							_path = sResult.GetDirectoryEntry().Path;
//////				
//////							ent = sResult.GetDirectoryEntry();
//////							ent.Invoke("ChangePassword", new object[] {oldPassword, newPassword});
//////							ent.CommitChanges();
//////							// END COPY
//////
//////							return true;
//////						}
//////						else
//////						{
//////							CloseHandle(tokenHandle);
//////							Console.WriteLine("Exception thrown in trying to duplicate token.");        
//////						}
//////					}
//////				}
//////				catch (Exception ex1)
//////				{
//////					Console.WriteLine (ex1.Message);
//////				}

				result = ex.Message;
				return false;
			}		
		}

		/// <summary>
		/// Returns the FullName property of a given UserID in a give Domain on the network. Also fills the Path and Properties properties with data. In order to access ActiveDirectory or LDAP, the function will use the credentials of the process calling it. Otherwise call the overloaded function with LDAP credentials.
		/// </summary>
		/// <param name="domain">the domain to be resolved in</param>
		/// <param name="UserID">the user id</param>
		/// <returns></returns>
		public string Resolve(string domain, string userID)
		{
			return Resolve(domain, userID, null, null, null);
		}
		

		/// <summary>
		/// Returns the FullName property of a given UserID in a give Domain on the network. Also fills the Path and Properties properties with data.
		/// </summary>
		/// <param name="domain">the domain to be resolved in</param>
		/// <param name="UserID">the user id</param>
		/// <returns></returns>
		public string Resolve(string domain, string UserID, string guestDomain, string guestUserID, string guestPassword)
		{
			string retVal;
			
			switch (_authtype)
			{
				case Authentication.AuthenticationTypes.ActiveDirectory:
					_path = "WinNT://" + domain;
					break;
				case Authentication.AuthenticationTypes.LDAP:
					_path = "LDAP://" + domain;
					break;
			}

//New CODE:
			DirectoryEntry ent = new DirectoryEntry();
			ent.Path = _path;
			if ((guestDomain != null) || (guestUserID != null) || (guestPassword != null))
			{
				ent.Username = guestDomain + "/" + guestDomain + "\\" + guestUserID;
				ent.Password = guestPassword;
			}

			ent.AuthenticationType = System.DirectoryServices.AuthenticationTypes.Secure;
			
			object obj1 = ent.NativeObject; /// makes sure the object is bound.

            DirectorySearcher Searcher = new DirectorySearcher(ent,"(sAMAccountName=" + UserID + ")");
			Searcher.SearchScope = SearchScope.Subtree;
			SearchResult result = Searcher.FindOne();

			System.DirectoryServices.PropertyCollection pc = result.GetDirectoryEntry().Properties;
			_path = result.GetDirectoryEntry().Path;
			
			_usrPropsDict = new System.Collections.SortedList();
			
			foreach(string name in pc.PropertyNames)
			{				
				_usrPropsDict.Add(name,pc[name][0]); //assign the value
				//http://www.microsoft.com/technet/scriptcenter/topics/win2003/lastlogon.mspx
				object o = pc[name][0]; //determine if the value is of type IADsLargeInteger
				if ((o as Interop.ActiveDS.IADsLargeInteger)!=null)
				{
					//Console.WriteLine (name + " is a IADSLargeInteger!");
					Interop.ActiveDS.IADsLargeInteger val = (Interop.ActiveDS.IADsLargeInteger)o;
					try
					{
						double dblDateTime = 0;
						DateTime newTime = new DateTime(1601,1,1);
						dblDateTime = (val.HighPart * (System.Math.Pow(2,32)));
						dblDateTime += val.LowPart;
						dblDateTime = dblDateTime / (60 * 10000000);
						dblDateTime = dblDateTime / 1440;
						//Console.WriteLine(dblDateTime);
						//Console.WriteLine (name + ": " + newTime.AddDays(dblDateTime));
						_usrPropsDict[name] = newTime;
					}
					catch (ArgumentOutOfRangeException ex) //i.e. - Account Expires = never.
					{
						Console.WriteLine(ex.ToString());
						_usrPropsDict[name] = false;
					}
					//Console.WriteLine(); 
				}
				
			}

			retVal = _usrPropsDict["displayName"].ToString();
			retVal = retVal.Trim();
		
			ent.Close();
			GC.Collect();
			return retVal;
		}

		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
			
		}

		
		#endregion

		#region Private Methods
private void Dispose(bool disposing)
	{
		if (disposing)
		{
			_usrPropsDict = null;
		}
		else
		{
		}
	}
private void Finalize()
	{
		Dispose(false);
	}
						
private System.Collections.SortedList GetDomains()
		{
			System.Collections.SortedList alTemp = new System.Collections.SortedList();
		
			switch (_authtype)
			{
				case Authentication.AuthenticationTypes.ActiveDirectory:
					_path = "WinNT:";
					break;
				case Authentication.AuthenticationTypes.LDAP:
					_path = "LDAP:";
					break;
			}
			DirectoryEntry entry = new DirectoryEntry(_path);
			foreach(DirectoryEntry d in entry.Children)
			{
				alTemp.Add(d.Name,d.Name);
			}
			entry.Close();
			GC.Collect();
			return alTemp;
		}
	
		#endregion
	
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -