/// <summary>
        /// Test AD connectivity
        /// </summary>
        /// <param name="user">User</param>
        private static void TestAD(UserInfo user)
        {
            LdapAuthentication adAuth = null;

            try
            {
                // Connection au LDAP pour vérifier le compte user
                adAuth = new LdapAuthentication(user.GetMessages());

                // Check
                adAuth.Test();

                // We are good here
                // Let's disconnect
            }
            finally
            {
                // On va fermer proprement la connexion
                // au serveur LDAP
                if (adAuth != null)
                {
                    try
                    {
                        adAuth.Disconnect();
                    }
                    catch (Exception) { } // On ignore cette erreur
                }
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //var userManager = context.OwinContext.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;
            //}


            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });


            var ldap = new LdapAuthentication();

            var response = ldap.connectToAD(context.UserName, context.Password, "Domain Users");


            if (response.Where(item => item != null).Any(item => item.Contains("Correct")))
            {
                _displayName = response[3];
                _userEmail   = response[4];
                _userName    = response[5];
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);

                identity.AddClaim(new Claim("sub", context.UserName));
                identity.AddClaim(new Claim("role", "user"));

                context.Validated(identity);
            }
        }
        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));
        }
Beispiel #4
0
        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());
        }
Beispiel #5
0
        /// <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);
        }
Beispiel #6
0
        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);
        }
Beispiel #7
0
        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;
            }
        }
Beispiel #8
0
        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 static IVaultService AuthenticateUsingLdap(this DefaultVaultService vaultService, string username, string password)
            {
                var auth = new LdapAuthentication(vaultService);

                auth.Credentials(username, password);
                vaultService.AuthenticateAsync(auth).ConfigureAwait(false).GetAwaiter().GetResult();
                return(vaultService);
            }
Beispiel #10
0
        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());
        }
Beispiel #11
0
    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 + ">";
            }
        }
    }
Beispiel #12
0
    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 = "登录失败,请检查用户名和密码!";
        }
    }
Beispiel #13
0
        /// <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);
        }
Beispiel #14
0
    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 = "登录失败,请检查用户名和密码!";
        }
    }
Beispiel #15
0
        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 Button1_Click(object sender, EventArgs e)
        {
            //mp1.Hide();

            try
            {
                SSAErrorLog        logObj     = new SSAErrorLog();
                LdapAuthentication ldapObj    = new LdapAuthentication();
                string             domainName = ConfigurationManager.AppSettings["domain"];
                string             displayVal = ldapObj.IsAuthenticatedStr(domainName, userNameTxt.Text, Session["pwd"].ToString());
                DatabaseLayer      dataObj    = new DatabaseLayer();


                logObj.ErrorLog(ConfigurationManager.AppSettings["logfilepath"].ToString(), "displayVal  " + displayVal);


                if (displayVal != null)
                {
                    Session["username"] = displayVal;

                    string userid = userNameTxt.Text.ToLower();
                    Session["pwd"]    = passwordTxt.Text;
                    Session["userid"] = userid;

                    // DatabaseLayer dataObj = new DatabaseLayer();
                    if (dataObj.getTablerowCount("userquestionanswers", "username='******'"))
                    {
                        Session["update"] = "yes";
                    }
                    else
                    {
                        Session["update"] = "no";
                    }

                    // Server.Transfer("SSAHome.aspx",true);
                    //update session object..
                    string updateStr = "update usersession set sessionobj='" + Session[AntiXsrfTokenKey] + "' ,logincounter=0 where userid='" + userNameTxt.Text + "'";
                    dataObj.insertTableData(updateStr);
                    Response.Redirect("SSAHome.aspx", false);
                }
                else
                {
                    Errorlabel.Text = "Authentication Failed !!!";
                    Session.RemoveAll();
                }
            }
            catch (Exception er)
            {
                Errorlabel.Text = "Authentication Failed !!!";
            }
        }
Beispiel #17
0
        private async Task <IActionResult> LoginByLdap(LoginInputModel model, AuthorizationRequest context)
        {
            var privateSettings = await _globalConfigurationAppService.GetPrivateSettings();

            var           ldap         = new LdapAuthentication(privateSettings.LdapSettings);
            UserViewModel userIdentity = null;

            try
            {
                userIdentity = ldap.Login(model.Username, model.Password);

                if (userIdentity.CustomClaims.ExistType(JwtClaimTypes.Name))
                {
                    userIdentity.Name = userIdentity.CustomClaims.GetValue(JwtClaimTypes.Name);
                }
                if (userIdentity.CustomClaims.ExistType("mail", JwtClaimTypes.Email))
                {
                    userIdentity.Email          = userIdentity.CustomClaims.GetValue("mail", JwtClaimTypes.Email);
                    userIdentity.EmailConfirmed = true;
                }

                userIdentity.CustomClaims.Remove("mail", JwtClaimTypes.Email, JwtClaimTypes.Name);
            }
            catch (Exception e)
            {
                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, e.Message));

                ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage);
            }

            if (userIdentity != null)
            {
                var result = await DoLogin(userIdentity, model.RememberLogin);

                if (result.Succeeded)
                {
                    return(await SuccessfullLogin(model, userIdentity, context));
                }
                else
                {
                    await FailedLogin(model, result, userIdentity);
                }
            }
            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
Beispiel #18
0
        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
                });
            }
        }
Beispiel #19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string adPath =
                "LDAP://ghadir.local/DC=ghadir,DC=local";
            LdapAuthentication adAuth = new LdapAuthentication(adPath);

            string logoninfo = Request.ServerVariables["LOGON_USER"];

            if (logoninfo.Length > 0)
            {
                Response.Write("<br> LOGON_USER : "******"<br>No User Info LOGON_USER");
            }

            logoninfo = Request.ServerVariables["REMOTE_HOST"];
            if (logoninfo.Length > 0)
            {
                Response.Write("<br> REMOTE_HOST : " + logoninfo);
            }
            else
            {
                Response.Write("<br>No User Info REMOTE_HOST");
            }
            logoninfo = Request.ServerVariables["AUTH_USER"];
            if (logoninfo.Length > 0)
            {
                Response.Write("<br> AUTH_USER :"******"<br>No User Info AUTH_USER");
            }

            logoninfo = Request.ServerVariables["HTTP_HOST"];
            if (logoninfo.Length > 0)
            {
                Response.Write("<br> HTTP_HOST :" + logoninfo);
            }
            else
            {
                Response.Write("<br>No User Info HTTP_HOST");
            }

            Response.Write("<br> Request.LogonUserIdentity.Name :" + Request.LogonUserIdentity.Name + "<hr><br>");
        }
    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;
    }
Beispiel #21
0
        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");
            }
        }
Beispiel #22
0
        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)
            {
            }
        }
Beispiel #23
0
        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);
        }
Beispiel #24
0
        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;
        }
Beispiel #25
0
        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);
            }
        }
Beispiel #26
0
        public UserEntity Login(string username, string passwd)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("Login").Add("UserName", username).ToInputLogString());
            UserEntity user = null;

            if (WebConfig.IsSkipAD())
            {
                if (CheckValidUser(username))
                {
                    user = GetUserByLogin(username);
                }
                else
                {
                    throw new CustomException(Resource.Msg_UserRoleNotFound);
                }
            }
            else
            {
                string result;
                using (var authen = new LdapAuthentication())
                {
                    result = authen.Login(username, passwd);
                }

                if ("SUCCESS".Equals(result))
                {
                    if (!CheckValidUser(username))
                    {
                        throw new CustomException(Resource.Msg_UserRoleNotFound);
                    }

                    Logger.Info(_logMsg.Clear().SetPrefixMsg("Login").ToSuccessLogString());
                    user = GetUserByLogin(username);
                }
                else
                {
                    Logger.Info(_logMsg.Clear().SetPrefixMsg("Login").ToFailLogString());
                }
            }

            return(user);
        }
        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;
            }
        }
Beispiel #28
0
        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);
        }
Beispiel #29
0
    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;
                }
            }
        }
    }
 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;
 }
Beispiel #31
0
        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();
                }
            }
        }
Beispiel #32
0
        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());
        }
        protected void Login_Click(object sender, EventArgs e)
        {
            DatabaseLayer dataObj = new DatabaseLayer();
            SSAErrorLog   logObj  = new SSAErrorLog();

            try
            {
                if (ConfigurationManager.AppSettings["captchavalidation"].ToString().Equals("yes"))
                {
                    if (txtimgcode.Text == Session["CaptchaImageText"].ToString())
                    {
                        //lblmsg.Text = "Excellent.......";
                    }
                    else
                    {
                        lblmsg.Text = "Please Enter valid Captcha.";
                        return;
                    }
                    this.txtimgcode.Text = "";
                }

                logObj.ErrorLog(ConfigurationManager.AppSettings["logfilepath"].ToString(), "Loggedin");

                LdapAuthentication ldapObj    = new LdapAuthentication();
                string             domainName = ConfigurationManager.AppSettings["domain"];

                string str = String.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);

                if (dataObj.getTablerowCount("usersession", "userid='" + userNameTxt.Text + "'"))
                {
                    ArrayList userArray1 = new ArrayList();

                    userArray1.Add("userid");
                    userArray1.Add("sessionobj");
                    userArray1.Add("createddate");
                    userArray1.Add("logincounter");
                    ArrayList userArray = dataObj.getTableDataQuery("userid,sessionobj,createddate,logincounter from usersession", "userid='" + userNameTxt.Text + "'", "idusersession", userArray1);
                    int       counter   = (int)Convert.ToInt64(userArray[3].ToString());
                    //DateTime createDate = (DateTime) userArray[2];
                    DateTime createDate    = Convert.ToDateTime(userArray[2].ToString());
                    DateTime currentDate   = DateTime.Now;
                    int      configCounter = (int)Convert.ToInt64(ConfigurationManager.AppSettings["nooftries"].ToString());
                    int      sessionLock   = (int)Convert.ToInt64(ConfigurationManager.AppSettings["sessionlock"].ToString());


                    string err = ConfigurationManager.AppSettings["sessionlockmsg"].ToString();

                    if (((currentDate - createDate).Minutes <= sessionLock) && (counter >= configCounter))
                    {
                        int    diffDate      = (currentDate - createDate).Minutes;
                        int    remainingTime = sessionLock - diffDate;
                        string errorMsg      = string.Format(err, remainingTime);
                        Errorlabel.Text = errorMsg; //"Please try after some time, User is locked due to no of tries are exceeded..";
                                                    //Response.Redirect("SSAHome.aspx");
                                                    // Session.RemoveAll();
                        return;
                    }

                    //Session[AntiXsrfTokenKey]
                    //userid,sessionobj,createddate

                    string updateStr = "update usersession set sessionobj='" + Session[AntiXsrfTokenKey] + "' ,logincounter=0 where userid='" + userNameTxt.Text + "'";

                    //dataObj.insertTableData("insert into usersession (userid,sessionobj,createddate,logincounter) values('" + userNameTxt.Text + "','" + Session[AntiXsrfTokenKey] + "','" + str + "',0)");
                    dataObj.insertTableData(updateStr);


                    //dataObj.insertTableData("insert into usersession (userid,sessionobj,createddate,logincounter) values('" + userNameTxt.Text + "','" + Session[AntiXsrfTokenKey] + "','" + str + "',0)" )                   ;

                    string displayVal = ldapObj.IsAuthenticatedStr(domainName, userNameTxt.Text, passwordTxt.Text);



                    logObj.ErrorLog(ConfigurationManager.AppSettings["logfilepath"].ToString(), "displayVal  " + displayVal);

                    //System.IO.File.WriteAllText(@"C:\SelfServiceAdminstration\login1.txt", "displayVal " + displayVal);
                    //userNameTxt.Text = "done ";
                    //Session["username"] = userNameTxt.Text;
                    if (displayVal != null)
                    {
                        //System.IO.File.WriteAllText(@"C:\SelfServiceAdminstration\login2.txt", "displayVal " + displayVal);
                        Session["username"] = displayVal;

                        string userid = userNameTxt.Text.ToLower();
                        Session["pwd"]    = passwordTxt.Text;
                        Session["userid"] = userid;

                        // DatabaseLayer dataObj = new DatabaseLayer();
                        if (dataObj.getTablerowCount("userquestionanswers", "username='******'"))
                        {
                            Session["update"] = "yes";
                        }
                        else
                        {
                            Session["update"] = "no";
                        }


                        Response.Redirect("SSAHome.aspx", false);
                    }
                    else
                    {
                        //userNameTxt.Text = "err";
                        Errorlabel.Text = "Authentication Failed !!!";
                        //Response.Redirect("SSAHome.aspx");
                        Session.RemoveAll();
                    }
                }
                else
                {
                    Hashtable userHash   = new Hashtable();
                    ArrayList userArray1 = new ArrayList();
                    userArray1.Add("userid");
                    userArray1.Add("sessionobj");
                    userArray1.Add("createddate");
                    userArray1.Add("logincounter");

                    //check the session here..
                    //userHash = dataObj.getTableData("usersession", userArray, "idusersession", "userid='" + userNameTxt.Text + "'");
                    //  ArrayList dataValues = dataObj.getTableDataQuery("", "userid='" + userNameTxt.Text + "'", "idusersession", userArray);
                    //get confirmation from request, If confirmed then login and update the session,
                    //else terminate this request.


                    // dialog.Visible = true;
                    Session["pwd"] = passwordTxt.Text;

                    // ArrayList userArray = dataObj.getTableDataQuery("userid,sessionobj,createddate,logincounter from usersession", "userid='" + userNameTxt.Text + "'", "idusersession", userArray1);
                    //  int counter = (int)Convert.ToInt64(userArray[3].ToString());
                    // DateTime createDate = Convert.ToDateTime(userArray[2].ToString());
                    //  DateTime currentDate = DateTime.Now;
                    int    configCounter = (int)Convert.ToInt64(ConfigurationManager.AppSettings["nooftries"].ToString());
                    int    sessionLock   = (int)Convert.ToInt64(ConfigurationManager.AppSettings["sessionlock"].ToString());
                    string err           = ConfigurationManager.AppSettings["sessionlockmsg"].ToString();

                    //LdapAuthentication ldapObj = new LdapAuthentication();
                    //string domainName = ConfigurationManager.AppSettings["domain"];
                    //string displayVal = ldapObj.IsAuthenticatedStr(domainName, userNameTxt.Text, Session["pwd"].ToString());
                    string displayVal = ldapObj.IsAuthenticatedStr(domainName, userNameTxt.Text, passwordTxt.Text);
                    if (displayVal != null)
                    {
                        Session["username"] = displayVal;

                        string userid = userNameTxt.Text.ToLower();
                        Session["pwd"]    = passwordTxt.Text;
                        Session["userid"] = userid;

                        // DatabaseLayer dataObj = new DatabaseLayer();
                        if (dataObj.getTablerowCount("userquestionanswers", "username='******'"))
                        {
                            Session["update"] = "yes";
                        }
                        else
                        {
                            Session["update"] = "no";
                        }

                        // Server.Transfer("SSAHome.aspx",true);
                        //update session object..
                        //string updateStr = "update usersession set sessionobj='" + Session[AntiXsrfTokenKey] + "' ,logincounter=0 where userid='" + userNameTxt.Text + "'";

                        dataObj.insertTableData("insert into usersession (userid,sessionobj,createddate,logincounter) values('" + userNameTxt.Text + "','" + Session[AntiXsrfTokenKey] + "','" + str + "',0)");
                        //dataObj.insertTableData(updateStr);
                        Response.Redirect("SSAHome.aspx", false);
                    }
                    else
                    {
                        Errorlabel.Text = "Authentication Failed !!!";
                        Session.RemoveAll();
                    }



                    /*
                     * if (((currentDate- createDate).Minutes <= sessionLock) && (counter >= configCounter))
                     * {
                     *  int diffDate = (currentDate - createDate).Minutes;
                     *  int remainingTime = sessionLock - diffDate;
                     *  string errorMsg = string.Format(err, remainingTime);
                     *  Errorlabel.Text = errorMsg;//"Please try after some time, User is locked due to no of tries are exceeded..";
                     *  //Response.Redirect("SSAHome.aspx");
                     * // Session.RemoveAll();
                     *  return;
                     * }
                     * else
                     * {
                     * // mp1.Show();
                     *  return;
                     * }
                     */


                    // userHash[]
                }


                /*
                 *
                 * string displayVal = ldapObj.IsAuthenticatedStr(domainName, userNameTxt.Text, passwordTxt.Text);
                 *
                 *
                 *
                 * logObj.ErrorLog(ConfigurationManager.AppSettings["logfilepath"].ToString(), "displayVal  " + displayVal);
                 *
                 * //System.IO.File.WriteAllText(@"C:\SelfServiceAdminstration\login1.txt", "displayVal " + displayVal);
                 * //userNameTxt.Text = "done ";
                 * //Session["username"] = userNameTxt.Text;
                 * if (displayVal != null)
                 * {
                 * //System.IO.File.WriteAllText(@"C:\SelfServiceAdminstration\login2.txt", "displayVal " + displayVal);
                 * Session["username"] = displayVal;
                 *
                 * string userid = userNameTxt.Text.ToLower();
                 * Session["pwd"] = passwordTxt.Text;
                 * Session["userid"] = userid;
                 *
                 * // DatabaseLayer dataObj = new DatabaseLayer();
                 * if (dataObj.getTablerowCount("userquestionanswers", "username='******'"))
                 * {
                 *     Session["update"] = "yes";
                 * }
                 * else
                 * {
                 *     Session["update"] = "no";
                 * }
                 *
                 * // Server.Transfer("SSAHome.aspx",true);
                 * Response.Redirect("SSAHome.aspx",false);
                 *
                 * }
                 * else
                 * {
                 * //userNameTxt.Text = "err";
                 * Errorlabel.Text = "Authentication Failed !!!";
                 * //Response.Redirect("SSAHome.aspx");
                 * Session.RemoveAll();
                 * }
                 */
            }
            catch (Exception er)
            {
                //userNameTxt.Text = "err";
                //  System.IO.File.WriteAllText(@"C:\SelfServiceAdminstration\login3.txt", "displayVal " + er.Message + "  StackTrace  " + er.StackTrace);
                logObj.ErrorLog(ConfigurationManager.AppSettings["logfilepath"].ToString(), "Error While authenticating   " + er.Message);
                Errorlabel.Text = "Authentication Failed !!!";
                //Session.RemoveAll();
            }
        }
        //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;
            }
        }