public UserAuthenticationModel UserAuthenticationLogin(string userName, string password, string contractorName) { String adPath = ConfigurationManager.AppSettings["LDAPServer"]; const string ERROR_MESSAGE = "User was unable to be authenticated. Please double check username and password. If problem persists, contact server administrator"; LdapAuthentication adAuth = new LdapAuthentication(adPath); try { var isAuthd = adAuth.IsAuthenticated(userName, password); if (isAuthd) { var user = new User() { Groups = adAuth.GetGroups().Split('|').ToList(), UserName = contractorName == null ? userName : contractorName + "-contractor" }; HttpContext.Current.Session.Add("User", user); HttpContext.Current.Session.Timeout = 30; var groups = adAuth.GetGroups(); // Create the ticket, and add the groups. var isCookiePersistent = false; var authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(120), isCookiePersistent, groups); // Encrypt the ticket. var encryptedTicket = FormsAuthentication.Encrypt(authTicket); return(new UserAuthenticationModel { IsAuthenticated = true, EncryptedTicket = encryptedTicket, CookieName = FormsAuthentication.FormsCookieName }); } return(new UserAuthenticationModel() { IsAuthenticated = false, ErrorMessage = ERROR_MESSAGE }); } catch (Exception ex) { return(new UserAuthenticationModel() { IsAuthenticated = false, ErrorMessage = ERROR_MESSAGE }); } }
public HttpResponseMessage Authenticate(string username, string password) { var obj = new ResponseModel(); string adPath = "LDAP://172.20.82.57,DC=urbanunit,DC=gov,DC=pk"; // "basitkhan", "Abc!2345" LdapAuthentication adAuth = new LdapAuthentication(adPath); try { if (true == adAuth.IsAuthenticated1("LDAP://172.20.82.57/OU=UrbanUnit,DC=urbanunit,DC=gov,DC=pk", username, password)) { //// Retrieve the user's groups string groups = adAuth.GetGroups("LDAP://172.20.82.57/OU=UrbanUnit,DC=urbanunit,DC=gov,DC=pk", username, password); var aduser = GetActiveDirectoryUserInfo(username, password); aduser.Groups = groups; obj.status = "200"; obj.message = "Login successfully"; obj.data = aduser; } else { //ViewBag.Error = "Authentication failed, check username and password."; obj.status = "400"; obj.message = "Authentication failed, check username and password."; } } catch (Exception ex) { //ViewBag.Error = "Error authenticating. " + ex.Message; obj.status = "500"; obj.message = "Error authenticating. " + ex.Message; } return(Request.CreateResponse(HttpStatusCode.OK, obj)); }
protected void LogIn(object sender, EventArgs e) { var ldapAuth = new LdapAuthentication(ConfigurationManager.AppSettings.Get("AWLDAP")); if (IsValid) { var domain = ConfigurationManager.AppSettings.Get("Domain"); var userName = txtUserID.Text; var splittedUserName = txtUserID.Text.Split('\\'); if (splittedUserName.Length > 1) { domain = splittedUserName[0]; userName = splittedUserName[1]; } var result = ldapAuth.IsAuthenticated(domain, userName, txtPassword.Text); if (result) { /////////////////////////////////////////////////////////// String groups = ldapAuth.GetGroups(domain, userName, txtPassword.Text); //Create the ticket, and add the groups. bool isCookiePersistent = false; FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups); //Encrypt the ticket. String encryptedTicket = FormsAuthentication.Encrypt(authTicket); //Create a cookie, and then add the encrypted ticket to the cookie as data. HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); if (true == isCookiePersistent) { authCookie.Expires = authTicket.Expiration; } //Add the cookie to the outgoing cookies collection. Response.Cookies.Add(authCookie); //You can redirect now. FormsAuthentication.RedirectFromLoginPage(userName, true); //Response.Redirect(FormsAuthentication.GetRedirectUrl(userName, false)); } else { ErrorMessage.Visible = true; FailureText.Text = "Authentication did not succeed. Check user name and password."; } //FormsAuthentication.RedirectFromLoginPage(userName, true); //Response.Redirect("Account/default.aspx"); } else { FailureText.Text = "Invalid login attempt"; ErrorMessage.Visible = true; } }
public ActionResult Logon(string txtUserName, string txtPassword) { // Path to you LDAP directory server. // Contact your network administrator to obtain a valid path. string adPath = "LDAP://hperrupato.com.ar/DC=hperrupato,DC=com,DC=ar"; LdapAuthentication adAuth = new LdapAuthentication(adPath); List <GruposAD> groups = new List <GruposAD>(); var cadena = ""; try { if (true == adAuth.IsAuthenticated("hperrupato", txtUserName, txtPassword)) { // Retrieve the user's groups groups = adAuth.GetGroups(); foreach (var item in groups) { cadena = cadena + item.grupo + "|"; } // Create the authetication ticket FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, // version txtUserName, DateTime.Now, DateTime.Now.AddMinutes(60), false, cadena); // Now encrypt the ticket. string encryptedTicket = FormsAuthentication.Encrypt(authTicket); // Create a cookie and add the encrypted ticket to the // cookie as data. HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); // Add the cookie to the outgoing cookies collection. Response.Cookies.Add(authCookie); // Redirect the user to the originally requested page Response.Redirect("~/Home/Index"); //Response.Redirect( //FormsAuthentication.GetRedirectUrl(txtUserName, //false)); } else { @ViewBag.Falla = "Incorrecto, revise usuario y contraseña"; } } catch (Exception ex) { @ViewBag.Falla = "Error de autenticación. " + ex.Message; } return(View()); }
protected void btnSubmit_Click(object sender, EventArgs e) { Boolean IsValid = false; if (txtLoginUserID.Text != "" && txtLoginPassword.Text != "") { IsValid = true; } if (IsValid) { HttpCookie roles = Request.Cookies["gcsroles"]; if (roles != null) { roles.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(roles); } string adPath = System.Configuration.ConfigurationManager.AppSettings["DefaultActiveDirectoryServer"]; LdapAuthentication adAuth = new LdapAuthentication(adPath); try { if (true == adAuth.IsAuthenticated("gcs-domain", txtLoginUserID.Text, txtLoginPassword.Text)) { // Retrieve the user's groups string groups = adAuth.GetGroups(); Session["theGroups"] = groups; // Create the authetication ticket FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, txtLoginUserID.Text, DateTime.Now, DateTime.Now.AddMinutes(60), false, groups); // Now encrypt the ticket. string encryptedTicket = FormsAuthentication.Encrypt(authTicket); // Create a cookie and add the encrypted ticket to the // cookie as data. HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); // Add the cookie to the outgoing cookies collection. Response.Cookies.Add(authCookie); Page.Session["username"] = txtLoginUserID.Text; // Redirect the user to the originally requested page Response.Redirect("/default.aspx"); } else { lblError.Text = "Authentication failed, check username and password."; } } catch (Exception ex) { lblError.Text = "Error authenticating. " + ex.Message; lblError.Text += "<br/><br/><a href=/" + Request.QueryString + ">"; } } }
protected void Login_Click(Object sender, EventArgs e) { String adPath = ConfigurationManager.AppSettings["LDAPServer"]; var adAuth = new LdapAuthentication(adPath); try { if (adAuth.IsAuthenticated(UserName.Text, Password.Text)) { var log = ObjectFactory.GetInstance <ILogger>(); log.LogAttempt(MethodBase.GetCurrentMethod().GetType(), OperationType.LOGIN, "LOGIN ATTEMPT", UserName.Text); String groups = adAuth.GetGroups(); // Create the ticket, and add the groups. bool isCookiePersistent = false; var authTicket = new FormsAuthenticationTicket(1, UserName.Text, DateTime.Now, DateTime.Now.AddMinutes(120), isCookiePersistent, groups); // Encrypt the ticket. String encryptedTicket = FormsAuthentication.Encrypt(authTicket); // Create a cookie, and then add the encrypted ticket to the cookie as data. HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); if (isCookiePersistent) { authCookie.Expires = authTicket.Expiration; } // Add the cookie to the outgoing cookies collection. Response.Cookies.Add(authCookie); // You can redirect now. Response.Redirect(FormsAuthentication.GetRedirectUrl(UserName.Text, false)); } else { Output.Text = "Authentication did not succeed. Either your user information is incorrect or you don't have permissions."; } } catch (Exception ex) { var log = ObjectFactory.GetInstance <ILogger>(); log.LogException(MethodBase.GetCurrentMethod().GetType(), OperationType.LOGIN, ex, ex.Message); Output.Text = "Error authenticating. " + ex.Message; } }
protected void Login_Click(Object sender, EventArgs e) { String adPathtemp = SetupFile.AD.ADRootPath; //Not necessary LdapAuthentication adAuthtemp = new LdapAuthentication(adPathtemp); String adPath = adAuthtemp.LDAPPath(); //get AD path from class LdapAuthentication adAuth = new LdapAuthentication(adPath); try { if (true == adAuth.IsAuthenticated(UserName.Text, Password.Text)) { String groups = adAuth.GetGroups(); //Create the ticket, and add the groups. bool isCookiePersistent = RememberMe.Checked; FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, UserName.Text, DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups); // Session["group"] = groups; //Encrypt the ticket. String encryptedTicket = FormsAuthentication.Encrypt(authTicket); //Create a cookie, and then add the encrypted ticket to the cookie as data. HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); if (true == isCookiePersistent) { authCookie.Expires = authTicket.Expiration; } //Add the cookie to the outgoing cookies collection. Response.Cookies.Add(authCookie); //You can redirect now. Response.Redirect(FormsAuthentication.GetRedirectUrl(UserName.Text, false)); } else { errorLabel.Text = "Authentication did not succeed. Check user name and password."; } } catch (Exception ex) { errorLabel.Text = "Error authenticating. " + ex.Message; } }
//method for log in button protected void ConfirmInsert_Click(object sender, EventArgs e) { // Path to LDAP directory server. try { //if text campus name is evesham, use the evesham domain if (txtCampus.Text == ("Evesham")) { string adPath = "LDAP://evesham.ac.uk"; LdapAuthentication adAuth = new LdapAuthentication(adPath); try { //if user is authenticated if (true == adAuth.IsAuthenticated(txtCampus.Text, TextUserName.Text, TextPassword.Text)) { // Retrieve the user's groups string groups = adAuth.GetGroups(); // Create the authetication ticket if (groups.Contains("EveshamCampusStudents") || groups.Contains("MalvernCampusStudents")) { FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, // version TextUserName.Text, DateTime.Now, DateTime.Now.AddSeconds(3), false, groups); // Now encrypt the ticket. string encryptedTicket = FormsAuthentication.Encrypt(authTicket); // Create a cookie and add the encrypted ticket to the // cookie as data. HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); // Add the cookie to the outgoing cookies collection. Response.Cookies.Add(authCookie); } else { FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, // version TextUserName.Text, DateTime.Now, DateTime.Now.AddMinutes(20), false, groups); // Now encrypt the ticket. string encryptedTicket = FormsAuthentication.Encrypt(authTicket); // Create a cookie and add the encrypted ticket to the // cookie as data. HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); // Add the cookie to the outgoing cookies collection. Response.Cookies.Add(authCookie); } //here, we will need to check if the staff belong in our database. //is not, we will need to get the information os the user from AD and insert it into our database //if user does not exists in our database, they will not be able to book an asset as the system cannot insert the booking due to table relation //we first need to get the staff table, then get the staff ID. That will be compared with the ID the user provided. //connection string string cs = System.Configuration.ConfigurationManager.ConnectionStrings["AssetBookingSystemConnectionString"].ConnectionString; //create new connection using the connection string SqlConnection con = new SqlConnection(cs); //create new sql command SqlCommand cmd = new SqlCommand(); //using reader SqlDataReader reader; //sql command text cmd.CommandText = "SELECT * FROM tblStaff"; //command type (could be sqlStored procedure, or a command text, we have the text here ) cmd.CommandType = CommandType.Text; cmd.Connection = con; //open connection and excute query con.Open(); reader = cmd.ExecuteReader(); //create table in the memory to store returned value from the database DataTable table = new DataTable(); table.Columns.Add("StaffID"); table.Columns.Add("StaffName"); //create new list to store count List <int> countList = new List <int>(); while (reader.Read()) { DataRow dataRow = table.NewRow(); //while reading, get the username provided by the user //and get the staff ID from the table string loggedUserName = TextUserName.Text; string userName = Convert.ToString(reader["StaffID"]); string name = Convert.ToString(reader["StaffName"]); dataRow["StaffID"] = userName; dataRow["StaffName"] = name; table.Rows.Add(dataRow); //for each row in the table foreach (DataRow dc in table.Rows) { //compare to see if the username and ID matech if (loggedUserName == userName) { //if so, add 1 to the list countList.Add(1); } } } //if the list is less than 1, it means the staff doesnt exists in the table. //in this case, we will need to get the staff information from AD and insert it into the table if (countList.Count < 1) { // enter AD settings PrincipalContext AD = new PrincipalContext(ContextType.Domain, "evesham.ac.uk"); // create search user and add criteria UserPrincipal u = new UserPrincipal(AD); u.SamAccountName = TextUserName.Text; // search for user PrincipalSearcher search = new PrincipalSearcher(u); UserPrincipal result = (UserPrincipal)search.FindOne(); search.Dispose(); // store the user name string fullName = result.DisplayName; string userName = TextUserName.Text; //connect to the database, and insert the staff detail string co = System.Configuration.ConfigurationManager.ConnectionStrings["AssetBookingSystemConnectionString"].ConnectionString; SqlConnection staffCon = new SqlConnection(co); string query = "INSERT INTO tblStaff (StaffID, StaffName)"; query += " VALUES (@userName, @fullName)"; SqlCommand insertStaff = new SqlCommand(query, staffCon); insertStaff.Parameters.AddWithValue("@userName", userName); insertStaff.Parameters.AddWithValue("@fullName", fullName); //open connection, excute query the close connection. staffCon.Open(); insertStaff.ExecuteNonQuery(); staffCon.Close(); } reader.Close(); con.Close(); // Redirect the user to the originally requested page //if the person belongs to an admin group, then redirect to admin page if (groups.Contains("a18")) { Response.Redirect("IndexManage.aspx"); } //if a person belongs to student group, redirect to information page if (groups.Contains("EveshamCampusStudents") || groups.Contains("MalvernCampusStudents")) { //lblStudentlogError.Visible = true; Response.Redirect("StudentLogInAttempt.aspx"); } //otherwise, redirect to normal booking page. else { Response.Redirect("Index.aspx"); } } } catch { lblError.Visible = true; } } //if the user is trying to log into malvern domain, do the same job as above, but using malvern domain for ldap else { string adPath = "LDAP://malvern.ac.uk"; LdapAuthentication adAuth = new LdapAuthentication(adPath); try { if (true == adAuth.IsAuthenticated(txtCampus.Text, TextUserName.Text, TextPassword.Text)) { // Retrieve the user's groups string groups = adAuth.GetGroups(); // Create the authetication ticket FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, // version TextUserName.Text, DateTime.Now, DateTime.Now.AddMinutes(60), false, groups); // Now encrypt the ticket. string encryptedTicket = FormsAuthentication.Encrypt(authTicket); // Create a cookie and add the encrypted ticket to the // cookie as data. HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); // Add the cookie to the outgoing cookies collection. Response.Cookies.Add(authCookie); //connection string string cs = System.Configuration.ConfigurationManager.ConnectionStrings["AssetBookingSystemConnectionString"].ConnectionString; //create new connection using the connection string SqlConnection con = new SqlConnection(cs); //create new sql command SqlCommand cmd = new SqlCommand(); //using reader SqlDataReader reader; //sql command text cmd.CommandText = "SELECT * FROM tblStaff"; //command type (could be sqlStored procedure, or a command text, we have the text here ) cmd.CommandType = CommandType.Text; cmd.Connection = con; //open connection and excute query con.Open(); reader = cmd.ExecuteReader(); //create table in the memory to store returned value from the database DataTable table = new DataTable(); table.Columns.Add("StaffID"); table.Columns.Add("StaffName"); List <int> countList = new List <int>(); while (reader.Read()) { DataRow dataRow = table.NewRow(); string loggedUserName = TextUserName.Text; string userName = Convert.ToString(reader["StaffID"]); string name = Convert.ToString(reader["StaffName"]); dataRow["StaffID"] = userName; dataRow["StaffName"] = name; table.Rows.Add(dataRow); foreach (DataRow dc in table.Rows) { if (loggedUserName == userName) { countList.Add(1); } } } if (countList.Count < 1) { // enter AD settings PrincipalContext AD = new PrincipalContext(ContextType.Domain, "malvern.ac.uk"); // create search user and add criteria UserPrincipal u = new UserPrincipal(AD); u.SamAccountName = TextUserName.Text; // search for user PrincipalSearcher search = new PrincipalSearcher(u); UserPrincipal result = (UserPrincipal)search.FindOne(); search.Dispose(); // show some details string fullName = result.DisplayName; string userName = TextUserName.Text; //if so, the user is trying to book the asset, so insert new record into the booking table string co = System.Configuration.ConfigurationManager.ConnectionStrings["AssetBookingSystemConnectionString"].ConnectionString; SqlConnection staffCon = new SqlConnection(co); string query = "INSERT INTO tblStaff (StaffID, StaffName)"; query += " VALUES (@userName, @fullName)"; SqlCommand insertStaff = new SqlCommand(query, staffCon); insertStaff.Parameters.AddWithValue("@userName", userName); insertStaff.Parameters.AddWithValue("@fullName", fullName); //open connection, excute query the close connection. staffCon.Open(); insertStaff.ExecuteNonQuery(); staffCon.Close(); } reader.Close(); con.Close(); // Redirect the user to the originally requested page //if the person belongs to an admin group, then redirect to admin page if (groups.Contains("a18")) { Response.Redirect("IndexManage.aspx"); } //if a person belongs to student group, redirect to information page if (groups.Contains("EveshamCampusStudents") || groups.Contains("MalvernCampusStudents")) { Response.Redirect("StudentLogInAttempt.aspx"); } //otherwise, redirect to normal booking page. else { Response.Redirect("Index.aspx"); } //FormsAuthentication.GetRedirectUrl(TextUserName.Text, // false)); } } catch { lblError.Visible = true; } } } catch { lblError.Visible = true; } }
/// <summary> /// Connexion à l'active Directory /// pour vérifier le compte utilisateur /// et reourner la liste des groupes auxquels /// cet dernier /// </summary> private void ConnectToLDAP() { LdapAuthentication adAuth = null; try { // Connection au LDAP pour vérifier le compte user adAuth = new LdapAuthentication(GetMessages()); if (!adAuth.UserExists(GetLogin(), GetPassword())) { // Le compte est introuvable // ou le login/mot de passe est erroné if (GetPassword() == null) { throw new Exception(GetMessages().GetString("LDAPUnknownUser", GetLogin(), true)); } else { throw new Exception(GetMessages().GetString("LDAPUnknownUserOrWrongPassword", GetLogin(), true)); } } // On a trouvé l'utilisation sur le serveur LDAP // On récupère son nom this.DisplayName = adAuth.GetDisplayName(); if (GetRequiredRigth() != UserInfo.RightNA) { // We need to check against a specific AD group for this application // First, let's extract all group Hashtable LDAPGroups = adAuth.GetGroups(); this.DisplayACardInLookupTool = LDAPGroups.ContainsValue(ConfigurationManager.AppSettings["CanDisplayACardInLookupTool"]); this.ProcessALookupInLookupTool = LDAPGroups.ContainsValue(ConfigurationManager.AppSettings["CanProcessALookupInLookupTool"]); this.ProcessAResverseLookup = LDAPGroups.ContainsValue(ConfigurationManager.AppSettings["CanProcessAResverseLookup"]); this.CreateATransactionalCard = LDAPGroups.ContainsValue(ConfigurationManager.AppSettings["CanCreateATransactionalCard"]); this.CreateAProfilCard = LDAPGroups.ContainsValue(ConfigurationManager.AppSettings["CanCreateAProfilCard"]); this.UpdateTokenAfterKeyRotation = LDAPGroups.ContainsValue(ConfigurationManager.AppSettings["CanUpdateTokenAfterKeyRotation"]); this.IsARobot = LDAPGroups.ContainsValue(ConfigurationManager.AppSettings["IsARobot"]); this.EncryptCard = LDAPGroups.ContainsValue(ConfigurationManager.AppSettings["CanEncryptCard"]); this.EncryptFOCard = LDAPGroups.ContainsValue(ConfigurationManager.AppSettings["CanEncryptFOCard"]); } } catch (Exception e) { // Erreur lors de la connexion au serveur LDAP throw new Exception(GetMessages().GetString("LDAPConnectionError", GetLogin(), e.Message, true)); } finally { // On va fermer proprement la connexion // au serveur LDAP if (adAuth != null) { try { adAuth.Disconnect(); } catch (Exception) { } // On ignore cette erreur } } }
private void Login_ADUser() { string userid = this.txtUserID.Text.Trim().ToLower();//登录人账户 string pwd = this.txtPwd.Text.Trim();//登录人密码 if (String.IsNullOrEmpty(userid) || String.IsNullOrEmpty(pwd)) { this.lblRegMsgPopup.Text = "用户名或密码错误,请从新输入!"; return; } string domain = ConfigurationManager.AppSettings["LdapAuthenticationDomain"].ToString(); LdapAuthentication ladAuthBP = new LdapAuthentication(); if (ladAuthBP.IsAuthenticated(domain, userid, pwd) && ladAuthBP.GetStatus()) { Hashtable userInfo = ladAuthBP.GetUserInfo(); string userDspName = (userInfo.Count > 0) ? userInfo["cn"].ToString() : ""; FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, "LoginCookieInfo", DateTime.Now, DateTime.Now.AddMinutes(60), false, userid); // User data string encryptedTicket = FormsAuthentication.Encrypt(authTicket); //加密 // 存入Cookie HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); authCookie.Expires = authTicket.Expiration; Response.Cookies.Add(authCookie); if (chkRemember.Checked)//再写入cookie { if (Request.Cookies["RememberMe"] == null || String.IsNullOrEmpty(Response.Cookies["RememberMe"].Value)) { Response.Cookies["RememberMe"].Value = HttpUtility.UrlEncode(userid, System.Text.Encoding.GetEncoding("gb2312")); Response.Cookies["RememberMe"].Expires = DateTime.Now.AddMonths(1); } } else { if (Response.Cookies["RememberMe"] != null) Response.Cookies["RememberMe"].Expires = DateTime.Now.AddDays(-1);//删除 } CommonFunction comFun = new CommonFunction(); comFun.setSesssionAndCookies(userid, userDspName, ladAuthBP.GetGroups()); this.Response.Redirect("~/Default.aspx"); } this.lblRegMsgPopup.Text = "用户名或密码错误,请从新输入!"; return; }