public ActionResult LogUserIn(LoginModel login) { string adPath = ConfigurationManager.AppSettings["connection_ldap"]; //Path to your LDAP directory server ViewBag.ldapaddress = adPath; LdapAuthentication adAuth = new LdapAuthentication(adPath); try { bool authed = false; authed = adAuth.IsAuthenticated("flinc", login.UserName, login.Password); if (authed) { // authorized User loggedInUser = DBAdapter.getInstance().GetUserByUsername(login.UserName); SessionAdapter.getInstance().LoggedInUser = loggedInUser; // Set the cookie FormsAuthentication.SetAuthCookie(login.UserName, true); ViewBag.hasBeenLoggedIn = "true"; } } catch (Exception ex) { // fail ModelState.AddModelError("", "The user name or password provided is incorrect."); ViewBag.hasBeenLoggedIn = "false"; } return(View()); }
/// <summary> /// 進行AD帳號驗證 使用FormsAuthenticationTicket驗證 /// </summary> /// <param name="logonModel"></param> /// <returns></returns> //private string ValidADAccountByFormsAuthenticationTicket(LogonViewModel logonModel) //{ // #region AD驗證 // var now = DateTime.Now; // string domainName = logonModel.DomainName; // string adValidMsg = string.Empty; // string adPath = "LDAP://" + domainName; // LdapAuthentication adAuth = new LdapAuthentication(adPath); // try // { // if (true == adAuth.IsAuthenticated(domainName, logonModel.Account, logonModel.Password)) // { // string groups = adAuth.GetGroups(); // //取出該會員的角色 // //string roles = string.Join(",", user.SystemRoles.Select(x => x.Name).ToArray()); // var ticket = new FormsAuthenticationTicket( // version: 1, // name: logonModel.Name, // issueDate: now, // expiration: now.AddMinutes(30), // isPersistent: logonModel.Remember, // userData: logonModel.Account, // cookiePath: FormsAuthentication.FormsCookiePath); // //表單門票加密 // var encryptedTicket = FormsAuthentication.Encrypt(ticket); // //放入cookie // var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); // Response.Cookies.Add(cookie); // } // else // { // adValidMsg = "請輸入正確的帳號或密碼!"; // } // } // catch (Exception ex) // { // adValidMsg = "請輸入正確的帳號或密碼!"; // } // #endregion AD驗證 // return adValidMsg; //} /// <summary> /// 進行AD帳號驗證 /// </summary> /// <param name="logonModel"></param> /// <returns></returns> private string ValidADAccountByCustom(LogonViewModel logonModel) { #region AD驗證 var now = DateTime.Now; string domainName = logonModel.DomainName; string adValidMsg = string.Empty; string adPath = "LDAP://" + domainName; LdapAuthentication adAuth = new LdapAuthentication(adPath); try { if (!adAuth.IsAuthenticated(domainName, logonModel.Account, logonModel.Password)) { adValidMsg = "請輸入正確的帳號或密碼!"; } } catch (Exception) { adValidMsg = "請輸入正確的帳號或密碼!"; } #endregion AD驗證 return(adValidMsg); }
private bool ValidateUserAgainstLDAP() { bool flag = false; try { if (!string.IsNullOrEmpty(txtUserName.Text.Trim())) { string adPath = "LDAP://gvkbio.com:389/DC=gvkbio,DC=com"; LdapAuthentication ldap = new LdapAuthentication(adPath); //Checking User credentials using LDAP Server. if (ldap.IsAuthenticated("GVKBIO", txtUserName.Text.Trim(), txtPassword.Text.Trim())) { flag = true; } } else { MessageBox.Show("User can't be null", GlobalVariables.MessageCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { ErrorHandling.WriteErrorLog(ex.ToString()); } return(flag); }
protected void loginBtn_Click(object sender, EventArgs e) { string adPath = "LDAP://ghadir.local/DC=ghadir,DC=local"; LdapAuthentication adAuth = new LdapAuthentication(adPath); try { if (true == adAuth.IsAuthenticated(txtDomainName.Text, txtUserName.Text, txtPassword.Text)) { // Redirect the user to the originally requested page Response.Redirect( FormsAuthentication.GetRedirectUrl(txtUserName.Text, false)); } else { lblError.Text = "Authentication failed, check username and password."; } } catch (Exception ex) { lblError.Text = "Error authenticating. " + ex.Message; } }
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 btnLogin_Click(object sender, EventArgs e) { //string adPath = "LDAP://DC=mb,DC=com"; //Path to your LDAP directory server LdapAuthentication adAuth = new LdapAuthentication(txtDomain.Text); try { if (true == adAuth.IsAuthenticated(txtDomain.Text, txtUsername.Text, txtPassword.Text)) //if(true) { // string groups = adAuth.GetGroups(); string groups = ""; //Create the ticket, and add the groups. bool isCookiePersistent = chkPersist.Checked; FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, txtUsername.Text, 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); HttpCookie loginNameCookie = new HttpCookie(ESB_COOKIE_LOGINNAME, txtUsername.Text); if (true == isCookiePersistent) { authCookie.Expires = authTicket.Expiration; loginNameCookie.Expires = DateTime.Now.AddDays(30); } //Add the cookie to the outgoing cookies collection. Response.Cookies.Add(authCookie); Response.Cookies.Add(loginNameCookie); //Esb授权校验 EsbAuthen(txtUsername.Text); //Server.Transfer("Default.aspx"); //You can redirect now. //Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, false)); Response.Redirect("Default.aspx", false); } else { errorLabel.Text = "登录失败,请检查用户名和密码!"; } } catch (System.Exception ex) { errorLabel.Text = "登录失败,请检查用户名和密码!"; } }
/// <summary> /// 域账户验证并登陆 /// </summary> /// <param name="userModel"></param> /// <returns></returns> public ReturnValueModel LoginSys(UserModel userModel) { ReturnValueModel rvm = new ReturnValueModel(); var mainInfo = userModel.UserName.Split('\\'); var doMain = mainInfo[0].ToUpper(); var userName = mainInfo[1]; var doMainPath = ""; switch (doMain) { case "KABI": doMainPath = ConfigurationManager.AppSettings["KABIPath"]; break; case "FNC": doMainPath = ConfigurationManager.AppSettings["NetcarePath"]; break; case "FME": doMainPath = ConfigurationManager.AppSettings["FMCPath"]; break; } if (string.IsNullOrEmpty(doMainPath)) { rvm.Success = false; rvm.Msg = "登录失败"; rvm.Result = false; return(rvm); } LdapAuthentication ldap = new LdapAuthentication(doMainPath); var isLdap = ldap.IsAuthenticated(doMain, userName, userModel.Password); if (!isLdap) { rvm.Success = false; rvm.Msg = "登录失败"; rvm.Result = false; return(rvm); } var token = HttpUtils.PostResponse <TokenModel>(TokenUrl, $"UserName={userModel.UserName}&grant_type=password"); rvm.Success = true; rvm.Msg = ""; rvm.Result = new { token }; return(rvm); }
protected void btnLogin_Click(object sender, EventArgs e) { //string adPath = "LDAP://DC=mb,DC=com"; //Path to your LDAP directory server LdapAuthentication adAuth = new LdapAuthentication(txtDomain.Text); try { if (true == adAuth.IsAuthenticated(txtDomain.Text, txtUsername.Text, txtPassword.Text)) //if(true) { // string groups = adAuth.GetGroups(); string groups = ""; //Create the ticket, and add the groups. bool isCookiePersistent = chkPersist.Checked; FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, txtUsername.Text, 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); HttpCookie loginNameCookie = new HttpCookie(ESB_COOKIE_LOGINNAME, txtUsername.Text); if (true == isCookiePersistent) { authCookie.Expires = authTicket.Expiration; loginNameCookie.Expires = DateTime.Now.AddDays(30); } //Add the cookie to the outgoing cookies collection. Response.Cookies.Add(authCookie); Response.Cookies.Add(loginNameCookie); //Esb授权校验 EsbAuthen(txtUsername.Text); //Server.Transfer("Default.aspx"); //You can redirect now. //Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, false)); Response.Redirect("Default.aspx", false); } else { errorLabel.Text = "登录失败,请检查用户名和密码!"; } } catch (System.Exception ex) { errorLabel.Text = "登录失败,请检查用户名和密码!"; } }
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; } }
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 bool IsValidLogin_SCIAD(Page _Page, string ADUserName, string ADPassword) { bool bRet = false; string adPath = "LDAP://dhaka.org"; LdapAuthentication adAuth = new LdapAuthentication(adPath); if (adAuth.IsAuthenticated("dhaka.org", ADUserName, ADPassword)) { bRet = true; } else { uh.ShowHTMLMessage(_Page, ErrorNumber.SetType(ErrorNumber.PermissionDenied, errorType.LoginError), "Login Failure. You are not authorized user!!"); bRet = false; } return(bRet); }
protected void btnsignin_Click(object sender, EventArgs e) { Session["user_authenticated"] = false; Session["AdminUser"] = false; string ldap_authentication = ConfigurationManager.AppSettings["ldap_authentication"]; if (ldap_authentication.ToUpper() == "OFF") { XmlDocument userlist = new XmlDocument(); string _xmlFilePath = Server.MapPath("~/xml/UserAuthentication.xml"); userlist.Load(_xmlFilePath); XmlNodeList usernodelist = userlist.SelectNodes("/users/user"); foreach (XmlNode usernode in usernodelist) { string username = usernode.Attributes["username"].Value.ToString().Trim(); string password = usernode.Attributes["password"].Value.ToString().Trim(); string full_name = usernode.Attributes["fullname"].Value.ToString().Trim(); if (username.Equals(login_userid.Value, StringComparison.CurrentCultureIgnoreCase) && password.Equals(login_password.Value)) { Session["user_authenticated"] = true; Session["username"] = username; Session["full_name"] = full_name; } } if ((bool)Session["user_authenticated"]) { Session["AdminUser"] = userAdmin.CheckAdminUserExistence(Session["username"].ToString()); } } else if (adAuth.IsAuthenticated("bp", login_userid.Value, login_password.Value)) { Session["user_authenticated"] = true; Session["username"] = login_userid.Value; Session["full_name"] = adAuth.RequestorFullName; } if ((bool)Session["user_authenticated"]) { Response.Redirect("BPS Crashes.aspx"); } else { string script = "ShowModal();"; ScriptManager.RegisterClientScriptBlock(this, typeof(System.Web.UI.Page), "ShowModal", getjQueryCode(script), true); } }
protected void btnLogin_Click(object sender, EventArgs e) { String adPath = System.Web.Configuration.WebConfigurationManager.AppSettings["adAuthURL"].ToString(); LdapAuthentication adAuth = new LdapAuthentication(adPath); try { if (true == adAuth.IsAuthenticated("ADMIN", txtUsername.Text, txtPassword.Text)) { } } catch (Exception ex) { loginErrors.InnerHtml = "Authentication did not succeed. Check user name and password."; loginErrors.Style.Remove("visibility"); } }
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; }
protected void Page_Load(object sender, EventArgs e) { //var la = new LdapAuthentication("LDAP://ldap.amwater.net/DC=amwaternp,DC=net,DC=amwater,DC=net"); //var la = new LdapAuthentication("LDAP://ldap.amwater.net"); //var la = new LdapAuthentication("LDAP://DC=amwater,DC=net"); var la = new LdapAuthentication("LDAP://DC=amwaternp,DC=net"); try { var x = la.IsAuthenticated("AWW", "DEYS", "Yad%1984"); } catch (Exception ex) { } }
private bool IsAuthenticatedUser(string networkId, string password) { try { LdapAuthentication authentication = new LdapAuthentication(); if (authentication.IsAuthenticated(networkId.ToLower().Trim(), password.Trim())) { return true; } } catch (Exception ex) { Logger.Error("Default > IsAuthenticatedUser\r\nMessage: " + ex.Message + "\r\nStackTrace: " + ex.StackTrace); } return false; }
public override RadiusPacket AccessRequestReceived(AccessRequest accessRequest, IPEndPoint client) { /*if (ServiceCfg.Instance.TinyConfig.ValidateByLdap) * { * string struser = accessRequest.UserName; * string strpwd = accessRequest.Password; * string path = ServiceCfg.Instance.TinyConfig.LdapSetting.Path; * * int type = RadiusPacket.AccessReject; * * var auth = new LdapAuthentication(path); * if (auth.IsAuthenticated(ServiceCfg.Instance.TinyConfig.LdapSetting.DomainName, struser, strpwd)) * { * type = RadiusPacket.AccessAccept; * } * * * if (type == RadiusPacket.AccessAccept) * { * var answer = new RadiusPacket(type, accessRequest.Identifier); * CopyProxyState(accessRequest, answer); * return answer; * } * }*/ string struser = accessRequest.UserName; string strpwd = accessRequest.Password; this.Logger.InfoFormat("通过Ldap检查用户,用户{0},密码{1}", struser, strpwd); if (!LdapAuthentication.IsAuthenticated(struser, strpwd)) { this.Logger.InfoFormat("用户(账户{0},密码{1})Ldap登录失败,尝试本地数据库登陆", struser, strpwd); return(base.AccessRequestReceived(accessRequest, client)); } else { this.Logger.InfoFormat("用户(账户{0},密码{1})Ldap登录成功.", struser, strpwd); const int type = RadiusPacket.AccessAccept; var answer = new RadiusPacket(type, accessRequest.Identifier); CopyProxyState(accessRequest, answer); return(answer); } }
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; } }
public LoginResponse Login(LoginRequest request) { var retval = new LoginResponse(); DateTime requesTime = DateTime.Now; try { var auth = new LdapAuthentication(ldapPath); retval.IsOK = auth.IsAuthenticated(request.Domain, request.Username, request.Password); retval.Message = "Login Success"; } catch (Exception ex) { retval.IsOK = false; retval.Message = ex.Message; } finally { LogHelper.AddLog(request.Username, request.Domain, retval.IsOK, retval.Message, requesTime); } return(retval); }
private bool IsADAuthenticated() { try { // LDAP Authentication if (true == adAuth.IsAuthenticated(domainName, UserId.Text, Password.Text)) { //Do whatever we want return(true); } else { FailureText.Text = "Authentication did not succeed. Check user name and password."; ErrorMessage.Visible = true; } } catch (Exception ex) { FailureText.Text = "Error authenticating. " + ex.Message; ErrorMessage.Visible = true; } return(false); }
/// <summary> /// 验证登录 /// </summary> /// <param name="account">账号</param> /// <param name="password">密码 MD5 32位 小写</param> /// <param name="domainlogin">是否域账户登录</param> /// <returns></returns> public UserEntity CheckLogin(string account, string password, string domainlogin) { try { UserEntity userEntity = GetEntityByAccount(account); if (userEntity == null) { userEntity = new UserEntity() { LoginMsg = "账户不存在!", LoginOk = false }; return(userEntity); } userEntity.LoginOk = false; if (userEntity.F_EnabledMark == 1) { if (domainlogin == "1") { #region 域身份认证 string adserver = Config.GetValue("adServer"); string adPath = "LDAP://" + adserver; LdapAuthentication adAuth = new LdapAuthentication(adPath); if (true == adAuth.IsAuthenticated(adserver, account, password)) { userEntity.LoginOk = true; return(userEntity); } else { userEntity.LoginMsg = "密码和账户名不匹配!"; } #endregion } else { string dbPassword = Md5Helper.Encrypt(DESEncrypt.Encrypt(password.ToLower(), userEntity.F_Secretkey).ToLower(), 32).ToLower(); if (dbPassword == userEntity.F_Password) { userEntity.LoginOk = true; } else { userEntity.LoginMsg = "密码和账户名不匹配!"; } } } else { userEntity.LoginMsg = "账户被系统锁定,请联系管理员!"; } return(userEntity); } catch (Exception ex) { if (ex is ExceptionEx) { throw; } else { throw ExceptionEx.ThrowBusinessException(ex); } } }
protected void btn_sumit_Click(object sender, EventArgs e) { AdminBSO adminBSO = new AdminBSO(); if (Session["LoginCount"] != null) { Session["LoginCount"] = Convert.ToInt32(Session["LoginCount"].ToString()) + 1; } int n = Convert.ToInt32(Session["LoginCount"].ToString()); if (!txtAdminUser.Text.Contains("\\")) { Admin objUser = adminBSO.GetAdminByAccountPass(txtAdminUser.Text.Trim(), txtAdminPass.Text.Trim()); if (objUser != null) { if (objUser.AdminActive == false) { Tool.Message(this.Page, "Tài khoản này chưa được kích hoạt! Xin liên hệ với quản trị hệ thống"); return; } else { //ducnmi - capcha if (Convert.ToInt32(Session["LoginCount"].ToString()) > 3) { if (Session["Random"] != null && txtCapcha.Text.ToLower() == Session["Random"].ToString().ToLower()) { Session["LoginCount"] = null; } else { Tool.Message(this.Page, "Mã xác nhận sai!"); return; } } m_UserValidation.SignIn(txtAdminUser.Text.Trim(), objUser.AdminID.ToString(), objUser.AdminOrganizationId, Session.SessionID, ((objUser.AdminName == "administrator") ? true : false)); if (Request.QueryString["url"] != null && Request.QueryString["url"] != string.Empty) { Response.Redirect((Request.QueryString["url"])); } else { Response.Redirect(Request.RawUrl); } } } else { Tool.Message(this.Page, "Tài khoản hoặc mật khẩu không đúng! Xin vui lòng nhập lại"); return; } } else { if (ConfigurationManager.AppSettings.Get("isLDAP").ToString() == "1") { //Path to your LDAP directory server string adPath = ConfigurationManager.AppSettings.Get("LdapDomain").ToString(); LdapAuthentication adAuth = new LdapAuthentication(adPath); try { if (txtAdminUser.Text.IndexOf("\\") > 0) { string domainName = txtAdminUser.Text.Substring(0, txtAdminUser.Text.IndexOf("\\")); if (adAuth.IsAuthenticated(txtAdminUser.Text.Substring(0, txtAdminUser.Text.IndexOf("\\")), txtAdminUser.Text.Substring(txtAdminUser.Text.IndexOf("\\") + 1), txtAdminPass.Text)) { Admin user = adminBSO.GetAdminById(txtAdminUser.Text.Trim()); if (user != null) { //ducnmi - capcha if (Convert.ToInt32(Session["LoginCount"].ToString()) > 3) { if (txtCapcha.Text.ToLower() == Session["Random"].ToString().ToLower()) { Session["LoginCount"] = null; } else { Tool.Message(this.Page, "Mã xác nhận sai!"); return; } } m_UserValidation.SignIn(txtAdminUser.Text.Trim(), user.AdminID.ToString(), user.AdminOrganizationId, Session.SessionID, ((user.AdminName == "administrator") ? true : false)); //string groups = adAuth.GetGroups(); ////Create the ticket, and add the groups. //bool isCookiePersistent = true; //FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, // txtAdminUser.Text.Substring(txtAdminUser.Text.IndexOf("\\") + 1), 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); if (Request.QueryString["url"] != null && Request.QueryString["url"] != string.Empty) { Response.Redirect((Request.QueryString["url"])); } else { Response.Redirect(Request.RawUrl); } } else { Tool.Message(this.Page, "Tài khoản hoặc mật khẩu không đúng! Xin vui lòng nhập lại"); return; } } else { Tool.Message(this.Page, "Tài khoản hoặc mật khẩu không đúng! Xin vui lòng nhập lại"); return; } } } catch (Exception ex) { Tool.Message(this.Page, "Tài khoản hoặc mật khẩu không đúng! Xin vui lòng nhập lại"); return; } } else { string sTen_TCap = this.Get_DomainAccount(); if (sTen_TCap != "") { string text1 = this.txtAdminUser.Text; string str = ""; str = text1; string[] strArray = text1.Split(new char[1] { '\\' }); string lpszDomain; string lpszUsername; if (strArray.Length == 2) { lpszDomain = strArray[0]; lpszUsername = strArray[1]; } else { lpszDomain = ((object)ConfigurationManager.AppSettings.Get("DomainName")).ToString(); lpszUsername = text1; } //Tool.Message(this.Page, "TK1: " + lpszDomain +"\\"+lpszUsername ); Admin user = adminBSO.GetAdminById(txtAdminUser.Text.Trim()); // User user = new UserService().FindByUserName(this.txtAdminUser.Text); if (user != null) { //ducnmi - capcha if (Convert.ToInt32(Session["LoginCount"].ToString()) > 3) { if (txtCapcha.Text.ToLower() == Session["Random"].ToString().ToLower()) { Session["LoginCount"] = null; } else { Tool.Message(this.Page, "Mã xác nhận sai!"); return; } } m_UserValidation.SignIn(txtAdminUser.Text.Trim(), user.AdminID.ToString(), user.AdminOrganizationId, Session.SessionID, ((user.AdminName == "administrator") ? true : false)); if (Request.QueryString["url"] != null && Request.QueryString["url"] != string.Empty) { Response.Redirect((Request.QueryString["url"])); } else { Response.Redirect(Request.RawUrl); } } else { Tool.Message(this.Page, "Tài khoản hoặc mật khẩu không đúng! Xin vui lòng nhập lại"); return; } } else { Tool.Message(this.Page, "Tài khoản hoặc mật khẩu không đúng! Xin vui lòng nhập lại"); return; } } } }
void btnSubmit_Click(object sender, EventArgs e) { try { string sMyIndentity = WindowsIdentity.GetCurrent().Name.ToString(); string myPCName = System.Net.Dns.GetHostName(); string strUsername = txtUsername.Text.Trim(); string strPassword = txtPassword.Text.Trim(); string adPath = Settings.Default.adPath; //Path to NCR LDAP directory server string sDomainValue = Settings.Default.DomainValue; //ENT LdapAuthentication adAuth = new LdapAuthentication(adPath); string sEmail = ""; if (true == adAuth.IsAuthenticated(sDomainValue, txtUsername.Text.Trim(), txtPassword.Text.Trim(), this.Page, true, out sEmail)) { if (sEmail.Trim() != "" && sEmail != null && sEmail != "0") { string sUserID = "0"; //UsersBO.Authenticate(strUsername, strPassword, out sUserID); //TODO: Uncomment when we get working with the sproc UsersBO.AuthenticateAfterLDAP(sEmail.Trim(), strUsername, out sUserID); FormsAuthentication.Initialize(); // Create the authentication ticket FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, // Ticket version strUsername, // Username to be associated with this ticket DateTime.Now, // Date/time issued DateTime.Now.AddMinutes(HttpContext.Current.Session.Timeout), // Date/time to expire false, // "true" for a persistent user cookie (could be a checkbox on form) CurrentUserRoles, // User-data (the roles from this user record in our database) FormsAuthentication.FormsCookiePath); // Path cookie is valid for // Hash the cookie for transport over the wire string hash = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie( FormsAuthentication.FormsCookieName, // Name of auth cookie (it's the name specified in web.config) hash); // Hashed ticket // Add the cookie to the list for outbound response Response.Cookies.Add(cookie); // Redirect to requested URL, or homepage if no previous page requested string returnUrl = Request.QueryString["ReturnUrl"]; if (returnUrl == null) { returnUrl = "~/Default.aspx"; } // Don't call the FormsAuthentication.RedirectFromLoginPage here, since it could // replace the custom authentication ticket we just added... Session["User_ID"] = sUserID; Session["FullName"] = CurrentUserName; Session["UserEnmail"] = sEmail.Trim(); Response.Redirect(returnUrl, false); } } else { throw new AppError("Login error: LDAP Authentication did not succeed. Check user name and password and try again."); } } catch (AppError err) { AddError(err); } catch (Exception ex) { AddError(ex); } finally { if (ErrorCount > 0) { //lblError.Text = GetErrors(); } } }
//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; } }
public async Task <ActionResult> Login(LoginViewModel usermodel) { if (!ModelState.IsValid) { return(View(usermodel)); } Microsoft.Owin.IOwinContext OwinContext = HttpContext.GetOwinContext(); //初始化用户管理相关 UserStore userStore = new UserStore(); UserDAL userdal = new UserDAL(); UserManager UserManager = new UserManager(userStore); //初始化权限管理相关 PermissionStore ps = new PermissionStore(); PermissionManager pm = new PermissionManager(ps); //登录 SignInManager signInManager = new SignInManager(UserManager, OwinContext.Authentication); Microsoft.AspNet.Identity.Owin.SignInStatus SignInStatus; string pass = usermodel.Password; string username = usermodel.LoginName; var user = new Com.HSJF.Infrastructure.Identity.Model.User { UserName = username, Password = pass }; byte[] _Key = Encoding.UTF8.GetBytes(WebConfigurationManager.AppSettings["Cryptokey"] ?? "HSJF!@#$12345678"); byte[] _IV = Encoding.UTF8.GetBytes(WebConfigurationManager.AppSettings["CryptoIV"] ?? "HSJF^%$#12345678"); SymmCrypto symm = new SymmCrypto(_Key, _IV); if (!userdal.FindUser(usermodel.LoginName, Convert.ToBase64String(symm.EncryptFromString(usermodel.Password)))) { ModelState.AddModelError("", "用户名不存在或者已被禁用!"); return(View()); } //域登陆 if (WebConfigurationManager.AppSettings["LoginMode"] == "LDAP") { LdapAuthentication ldap = new LdapAuthentication(); if (!ldap.IsAuthenticated(usermodel.LoginName, usermodel.Password)) { ModelState.AddModelError("", "用户名或者密码错误!"); return(View()); } var newuser = UserManager.FindByName(username); user.Password = symm.DecryptToString(Convert.FromBase64String(newuser.Password)); } SignInStatus = await PrivateLogin(user.UserName, user.Password); switch (SignInStatus) { //成功 case Microsoft.AspNet.Identity.Owin.SignInStatus.Success: //此处表示已经在startup 中配置 //标示 //System.Security.Claims.ClaimsIdentity identity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); //授权登陆 //AutherticationManager.SignIn(new Microsoft.Owin.Security.AuthenticationProperties { IsPersistent = true }, identity); System.Web.HttpContext.Current.Session["_currentUser"] = signInManager.UserManager.FindByName(user.UserName); return(RedirectToAction("Index", "Home")); //锁定 case Microsoft.AspNet.Identity.Owin.SignInStatus.LockedOut: Response.Write("LockedOut!"); break; //要求验证 case Microsoft.AspNet.Identity.Owin.SignInStatus.RequiresVerification: Response.Write("RequiresVerification!"); break; //登录失败 case Microsoft.AspNet.Identity.Owin.SignInStatus.Failure: ModelState.AddModelError("", @"用户名或者密码错误!"); return(View()); } return(View()); }
public bool IsValidLogin_SCIAD(Page _Page, string ADUserName, string ADPassword) { bool bRet = false; string adPath = "LDAP://dhaka.org"; LdapAuthentication adAuth = new LdapAuthentication(adPath); if (adAuth.IsAuthenticated("dhaka.org", ADUserName, ADPassword)) bRet = true; else { uh.ShowHTMLMessage(_Page, ErrorNumber.SetType(ErrorNumber.PermissionDenied, errorType.LoginError), "Login Failure. You are not authorized user!!"); bRet = false; } return bRet; }
public ActionResult Login(Model.LoginModel model, string returnUrl) { var IsLogin = ""; try { if (ModelState.IsValid) { string[] SplitAccount = new string[] { }; var username = ""; Entity.advt_users users = new advt_users(); Regex RegEmail = new Regex(@"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?");//w 英文字母或数字的字符串,和 [a-zA-Z0-9] 语法一样 Match m = RegEmail.Match(model.UserName); //工号 var wuser = Data.ExamUsersFromehr.Get_ExamUsersFromehr(new { UserCode = model.UserName }); if (wuser != null) { Service.IProvider.IAuthorizationServices services = new Service.Provider.AuthorizationServices(); users = services.EmailAuthenticate(wuser.CommpanyEmail, model.Password); if (users != null) //验证通过 { username = wuser.EamilUsername; } else { IsLogin = "******"; } } var cuser = Data.ExamUsersFromehr.Get_ExamUsersFromehr(new { EamilUsername = model.UserName }); if (cuser != null) { var acc = "acn\\" + cuser.EamilUsername.Trim(); SplitAccount = acc.Split('\\'); username = cuser.EamilUsername; } if (cuser != null) { if (SplitAccount.Length > 1) { String adPath = ""; //Fully-qualified Domain Name switch (SplitAccount[0].ToLower().Trim()) { case "acn": adPath = "LDAP://acn.advantech.corp"; //acn break; case "aeu": adPath = "LDAP://aeu.advantech.corp"; //advantech break; case "aus": adPath = "LDAP://aus.advantech.corp"; //advantech break; case "advantech": adPath = "LDAP://advantech.corp"; //advantech break; default: adPath = "LDAP://acn.advantech.corp"; //acn break; } LdapAuthentication adAuth = new LdapAuthentication(adPath); string password = model.Password.Trim(); if (true == adAuth.IsAuthenticated(SplitAccount[0], SplitAccount[1], model.Password)) { Service.IProvider.IAuthorizationServices service = new Service.Provider.AuthorizationServices(); users = service.Authenticate(username, model.Password); } else { IsLogin = "******"; } } } if (wuser == null && cuser == null) { IsLogin = "******"; } if (string.IsNullOrEmpty(IsLogin) && !string.IsNullOrEmpty(users.username)) { SetUserAuthIn(users.username.ToString(), users.password, string.Empty, false); //写入Cookie,无需登入。 var LF = Guid.NewGuid().ToString(); //写内存 Manager.Login.Lock_Flag = LF; //写本地 Utils.WriteCookie("ALock", LF); users.msn = LF; advt.Data.advt_users.Update_advt_users(users, null, new string[] { "id" }); XUtils.WriteUserCookie(users, model.CookieTime ?? 0, Config.BaseConfigs.Passwordkey, 1); IsLogin = "******"; } } } catch (Exception ex) { return(Json(new { IsLogin = ex.Message }, JsonRequestBehavior.AllowGet)); throw; } //ModelState.AddModelError("", "用户名或者密码错误!"); return(Json(new { IsLogin }, JsonRequestBehavior.AllowGet)); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { ///Author:Sushil Ghimire ///Purpose:Used To Enable CORS for Authorization Server and End Point /token var allowedOrigin = "*"; context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); #region Previous Code : Uses Identity to validate user //var userManager=HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>(); //ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); //if (user == null) //{ // context.SetError("invalid_grant", "The user name or password is incorrect."); // return; //} ////if (!user.EmailConfirmed) ////{ //// context.SetError("invalid_grant", "User did not confirm email."); //// return; ////} //ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT"); //var ticket = new AuthenticationTicket(oAuthIdentity, null); //context.Validated(ticket); #endregion #region Domain Authentication //Author: Ram K Thapa string domainName = context.UserName.Split('@')[1] == null ? "" : context.UserName.Split('@')[1].ToString(); string adPath = string.Concat("LDAP://", domainName); LdapAuthentication adAuth = new LdapAuthentication(adPath); try { if (false == adAuth.IsAuthenticated("spi", context.UserName, context.Password)) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } } catch (System.Exception ex) { context.SetError("invalid_grant", "The user name or password is incorrect."); } #endregion #region Retrieve User Information and Add to Claim string UserRoleId = string.Empty, UserName = string.Empty; var identity = new ClaimsIdentity(context.Options.AuthenticationType); var userInfo = UserInfoService.Instance.GetUserInfoByEmail(context.UserName); if (userInfo != null) { UserRoleId = userInfo.UsersUserRoleRels == null ? "" : userInfo.UsersUserRoleRels.FirstOrDefault().UserRole.UserRoleID.ToString(); UserName = userInfo.UserName; } identity.AddClaim(new Claim(ClaimTypes.Email, context.UserName)); identity.AddClaim(new Claim(ClaimTypes.Role, UserRoleId)); identity.AddClaim(new Claim(ClaimTypes.Name, UserName)); #endregion context.Validated(identity); }