• Decrease Text SizeIncrease Text Size

How do I setup custom LDAP Authentication

Posted Date: 5/10/2023
    Printer Friendly Version   Email A Friend   Add This   Increase Text Size   Decrease Text Size
set up LDAP Authentication text will go here
Navigate to Console > Admin > Global Login. Create a new record.
Source = Custom
Type = Centralpoint.WebSite.Custom.CustomAuthenticationSource
Parameters = (you can pass directory path. Example: DC=gha)



using Centralpoint.Web;
using Centralpoint.WebSite.Modules;
using System;
using System.Data.SqlClient;
using System.DirectoryServices;
using System.Web;

namespace Centralpoint.WebSite.Custom
{
    /// <summary>
    /// This class accesses the template authentication sources.
    /// </summary>
    public class CustomAuthenticationSource : Centralpoint.WebSite.Modules.ICustomAuthenticationSource
	{
		public string IntegrationId { get; set; }
		public string Email { get; set; }
		public string DisplayName { get; set; }
		public DateTime StartDate { get; set; }
		public DateTime EndDate { get; set; }
		public string[] AudienceIds { get; set; }
		public string AllAudiencesIntegrationId { get; set; }
		public string[] AudienceIntegrationIds { get; set; }
		public string[] RoleIds { get; set; }
		public string[] RoleIntegrationIds { get; set; }
		public CpCollection Properties { get; set; }
		public CpCollection Personalization { get; set; }
		public CpCollection Configuration { get; set; }


		/// <summary>
		/// This method is the default constructor.
		/// </summary>
		public CustomAuthenticationSource()
		{
			this.AllAudiencesIntegrationId = "ALL_AUDIENCES";
		}

		public bool IsAuthenticated()
		{
			return true;
		}

		/// <summary>
		/// This method access the custom authentication source and authenticates the user.
		/// </summary>
		/// <param name="source">The Admin > Global Login record that is currently in use.
		/// <param name="username">The users username.
		/// <param name="password">The users password.
		/// <returns>Whether the user has been sucessfully authenticated.</returns>
		public bool Authenticate(DataInfo source, string username, string password)
		{
			try
			{
				string parameters = source.Attributes.Get("CustomParameters");

				string directoryPath = parameters.Trim();
				if (String.IsNullOrEmpty(directoryPath))
				{
					DirectoryEntry root = new DirectoryEntry("LDAP://RootDSE");
					using (root)
					{
						//HttpContext.Current.Trace.Warn("DirectoryEntry:root", String.Format("{0}", root.Properties["defaultNamingContext"][0].ToString()));
						directoryPath = root.Properties["defaultNamingContext"][0].ToString();
					}
				}
	
				HttpContext.Current.Trace.Warn("directoryPath2", directoryPath);
				bool bSucceeded = false;
				string strError = String.Empty;
				DirectoryEntry adsEntry = new DirectoryEntry("LDAP://" + directoryPath, AuthenticationSources.LdapDNEscape(username), AuthenticationSources.LdapDNEscape(password));
				DirectorySearcher adsSearcher = new DirectorySearcher(adsEntry);
				adsSearcher.Filter = "(SAMAccountName=" + AuthenticationSources.LdapFilterEscape(username) + ")";

				string firstName = String.Empty;
				string userId = String.Empty;
				string lastName = String.Empty;
				string email = String.Empty;
				string displayName = String.Empty;
				try
				{
					SearchResult sr = adsSearcher.FindOne();
					firstName = (sr.Properties["givenname"].Count > 0) ? sr.Properties["givenname"][0].ToString() : String.Empty;
					lastName = (sr.Properties["sn"].Count > 0) ? sr.Properties["sn"][0].ToString() : String.Empty;
					email = String.Empty;
					if ((sr.Properties["mail"].Count > 0))
						email = sr.Properties["mail"][0].ToString();

					if (String.IsNullOrEmpty(email) && username.Equals("VGantman", StringComparison.CurrentCultureIgnoreCase))
						email = username + "@oxcyon.com";
					else if (String.IsNullOrEmpty(email) && !username.Equals("VGantman", StringComparison.CurrentCultureIgnoreCase))
						email = username + "@trihealth.com";
					userId = sr.GetDirectoryEntry().Guid.ToString();

					displayName = firstName + " " + lastName;
					if (String.IsNullOrEmpty(displayName)) displayName = username;

					bSucceeded = true;

					strError = "User has been authenticated by Active Directory.";
					adsEntry.Close();
				}
				catch (Exception ex)
				{
					// Failed to authenticate. Most likely it is caused by unknown user
					// id or bad Password.
					bSucceeded = false;
					strError = ex.Message;
					adsEntry.Close();
				}

				HttpContext.Current.Trace.Warn("bSucceeded", bSucceeded.ToString() + " strError: " + strError);
				//here you can call you your custom authentication source passing "username" and "password" and based on results set user information.
				// if user was found and can login you need to return true otherwise return false
				HttpContext.Current.Trace.Warn("username", username);

				if (bSucceeded)
				{
					bool userExists = false;
					string userName = username;
					string sql = String.Format("SELECT UserId,Email,IntegrationId,StartDate,EndDate FROM cpsys_Users WHERE (IsLockedOut = 0) AND (IsDeleted = 0) AND (GETUTCDATE() BETWEEN StartDate AND EndDate) AND AuthenticationSourcesDataId IS NULL AND (IntegrationId = '{0}' OR UserName='{0}')", userName.SqlEncode());
					using (SqlConnection connect = new SqlConnection(Management.Application.SelectConnectionString))
					{
						connect.Open();
						SqlCommand command = new SqlCommand(sql, connect);
						using (SqlDataReader reader = command.ExecuteReader())
						{
							userExists = reader.HasRows;
							if (reader.Read())
								this.IntegrationId = "cpsys_DoNotIntegrate:" + reader.GetGuid(0).ToString();
							else
								return false;
						}
					}

					HttpContext.Current.Trace.Warn(" this.IntegrationId", this.IntegrationId);
					return userExists;
				}
				else
					return false;
			}
			catch (Exception ex)
			{
				HttpContext.Current.Trace.Warn("Error", ex.Message);
				HttpContext.Current.Trace.Warn("Error", ex.StackTrace);
				return false;
			}
		}

		public static Guid GetAuthenticationSourcesDataId()
		{
			return new Guid("10eba9d9-b26b-496c-a908-09e6163aa92d");
		}
	}
}







Keywords: LDAP, Authentication, LDAP Authentication



Related Taxonomy
  - How Do I?

Comments:

Be the first to leave a comment.
Please Login to post comments.