Beispiel #1
1
        /// <summary>
        /// �û���¼����
        /// </summary>
        /// <param name="username">�û���</param>
        /// <param name="roles">�û���ɫ</param>
        /// <param name="isPersistent">�Ƿ�־�cookie</param>
        public static void Login(string username, string roles, bool isPersistent)
        {
            DateTime dt = isPersistent ? DateTime.Now.AddMinutes(99999) : DateTime.Now.AddMinutes(60);
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                                                                                1, // Ʊ�ݰ汾��
                                                                                username, // Ʊ�ݳ�����
                                                                                DateTime.Now, //����Ʊ�ݵ�ʱ��
                                                                                dt, // ʧЧʱ��
                                                                                isPersistent, // ��Ҫ�û��� cookie
                                                                                roles, // �û����ݣ�������ʵ�����û��Ľ�ɫ
                                                                                FormsAuthentication.FormsCookiePath);//cookie��׷��

            //ʹ�û�����machine key����cookie��Ϊ�˰�ȫ����
            string hash = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); //����֮���cookie

            //��cookie��ʧЧʱ������Ϊ��Ʊ��tikets��ʧЧʱ��һ��
            HttpCookie u_cookie = new HttpCookie("username", username);
            if (ticket.IsPersistent)
            {
                u_cookie.Expires = ticket.Expiration;
                cookie.Expires = ticket.Expiration;
            }

            //���cookie��ҳ��������Ӧ��
            HttpContext.Current.Response.Cookies.Add(cookie);
            HttpContext.Current.Response.Cookies.Add(u_cookie);
        }
Beispiel #2
1
        private void login(string userName, string password)
        {
            Model.User userObj = Model.Repositories.UsersRepository.GetUserByCredentials(userName, password);
            if (userObj == null)
                return;

            int userID = userObj.ID;
            string userRoles = "";
            foreach (Model.UserRole userRole in userObj.UserRoles)
            {
                if (userRoles == "")
                    userRoles = userRole.ID.ToString();
                else
                    userRoles += "," + userRole.ID.ToString();
            }

            if (userRoles == "")
                return;

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userID.ToString(), DateTime.Now,
                                                                             DateTime.Now.AddMinutes(30), false,
                                                                             userRoles,
                                                                             FormsAuthentication.FormsCookiePath);

            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));

            if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
            Response.Cookies.Add(cookie);

            string returnUrl = Request.QueryString["ReturnUrl"];
            if (String.IsNullOrEmpty(returnUrl))
                returnUrl = "Default.aspx";
            Response.Redirect(returnUrl);
        }
Beispiel #3
1
        public ActionResult LogOn(LoginModel model, string returnUrl)
        {
            ViewBag.Message = "Please enter username and password for login.";
            if (ModelState.IsValid)
            {
                User user = ValidateUser(model.username, model.password);

                if (user != null)
                {

                    var authTicket = new FormsAuthenticationTicket(1, model.username, DateTime.Now, DateTime.Now.AddMinutes(30), model.RememberMe,
                                                                "1");
                    string cookieContents = FormsAuthentication.Encrypt(authTicket);
                    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
                    {
                        Expires = authTicket.Expiration,
                        Path = FormsAuthentication.FormsCookiePath
                    };
                    Response.Cookies.Add(cookie);

                    if (!string.IsNullOrEmpty(returnUrl))
                        Response.Redirect(returnUrl);

                    return RedirectToAction("Index", "Dashboard");
                }
                else
                {
                    ViewBag.Message = "The user name or password provided is incorrect. Please try again";
               }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Beispiel #4
1
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {

            Session["Notification"] = "";
            if (ModelState.IsValid)
            {
                KIREIP.Core.Manager.UserManager CM = new KIREIP.Core.Manager.UserManager();
                KIREIP.Core.DAL.Login usr = CM.LoginUser(model.UserName, model.Password);
                if (usr != null)
                {
                    FormsAuthentication.Initialize();
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, usr.UserName.ToString(), DateTime.Now, DateTime.Now.AddMinutes(30), model.RememberMe, FormsAuthentication.FormsCookiePath);
                    string hash = FormsAuthentication.Encrypt(ticket);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
                    if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
                    Response.Cookies.Add(cookie);
                    if ((!String.IsNullOrEmpty(returnUrl)) && returnUrl.Length > 1)
                        return Redirect(returnUrl);
                    else
                    {
                        return RedirectToAction("Index", "Message");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Incorrect user name or password.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public ActionResult SignIn(SignInViewModel logInViewModel)
        {
            if (ModelState.IsValid)
            {
                string errorMessage;
                User user = _accountService.ValidateUser(logInViewModel.UserName, logInViewModel.Password, out errorMessage);
                if (user != null)
                {
                    SimpleSessionPersister.Username = user.Username;
                    SimpleSessionPersister.Roles = user.Roles.Select(x => x.Name).ToList();
                    if (logInViewModel.StayLoggedIn)
                    {
                        FormsAuthenticationTicket formsAuthenticationTicket = new FormsAuthenticationTicket(SimpleSessionPersister.Username, true, 10080);
                        string encrypt = FormsAuthentication.Encrypt(formsAuthenticationTicket);
                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypt);
                        Response.Cookies.Add(cookie);
                    }

                    return RedirectToAction("Index", "Feed");
                }
                ModelState.AddModelError(string.Empty, errorMessage);
            }

            return View();
        }
        public virtual void SignIn(Customer customer, bool createPersistentCookie)
        {
            var now = DateTime.UtcNow.ToLocalTime();

            var ticket = new FormsAuthenticationTicket(
                1 /*version*/,
                _customerSettings.UsernamesEnabled ? customer.Username : customer.Email,
                now,
                now.Add(_expirationTimeSpan),
                createPersistentCookie,
                _customerSettings.UsernamesEnabled ? customer.Username : customer.Email,
                FormsAuthentication.FormsCookiePath);

            var encryptedTicket = FormsAuthentication.Encrypt(ticket);

            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            cookie.HttpOnly = true;
            if (ticket.IsPersistent)
            {
                cookie.Expires = ticket.Expiration;
            }
            cookie.Secure = FormsAuthentication.RequireSSL;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            if (FormsAuthentication.CookieDomain != null)
            {
                cookie.Domain = FormsAuthentication.CookieDomain;
            }

            _httpContext.Response.Cookies.Add(cookie);
            _cachedCustomer = customer;
        }
        public ActionResult Login(LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            if (!new Services.LoginService().LoginValidation(model))
            {
                ModelState.AddModelError("", "無效的帳號或密碼兒");
                return(View());
            }

            //FormsAuthentication.RedirectFromLoginPage(model.帳號,false);
            //FormsAuthentication.SetAuthCookie(model.帳號, false);
            //return Redirect(FormsAuthentication.GetRedirectUrl(model.帳號, false));



            var ticket = new System.Web.Security.FormsAuthenticationTicket(
                version: 1,
                name: model.帳號,                                        //可以放使用者Id
                issueDate: DateTime.UtcNow,                            //現在UTC時間
                expiration: DateTime.UtcNow.AddMinutes(30),            //Cookie有效時間=現在時間往後+30分鐘
                isPersistent: true,                                    // 是否要記住我 true or false
                userData: "超級賽亞人",                                     //可以放使用者角色名稱
                cookiePath: System.Web.Security.FormsAuthentication.FormsCookiePath);
            var encryptedTicket = FormsAuthentication.Encrypt(ticket); //把驗證的表單加密

            //var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket));
            return(RedirectToAction("Index", "Home"));
            //return Redirect(FormsAuthentication.GetRedirectUrl(ticket.Name, false));
        }
        public void LogIn(string username, string password)
        {
            if (username == "lvs" && password == "Pass@word1")
            {
                FormsAuthentication.Initialize();
                FormsAuthentication.SetAuthCookie(username, false);
                var ticket = new FormsAuthenticationTicket(
                   1, // Ticket version
                   username, // Username associated with ticket
                   DateTime.Now, // Date/time issued
                   DateTime.Now.AddMinutes(30), // Date/time to expire
                   true, // "true" for a persistent user cookie
                   "", // User-data, in this case the roles
                   FormsAuthentication.FormsCookiePath);// Path cookie valid for

                // Encrypt the cookie using the machine key for secure transport
                string hash = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(
                   FormsAuthentication.FormsCookieName, // Name of auth cookie
                   hash); // Hashed ticket

                // Set the cookie's expiration time to the tickets expiration time
                if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;

                // Add the cookie to the list for outgoing response
                Response.Cookies.Add(cookie);

            }
        }
        /// <summary>
        /// Authenticate with twitter
        /// </summary>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        public ActionResult TwitterLogOn(string returnUrl)
        {
            UserService userService = new UserService(); ;
            string screenName;
            int userId;
            if (TwitterConsumer.TryFinishSignInWithTwitter(out screenName, out userId))
            {
                UserDetails user = userService.CreateUserIfNew(screenName, AuthenticationProvider.Twitter);
                /* We use custom principals and identities, store the userdetails in cookie
                 * See http://stackoverflow.com/a/10524305/48025 for details */
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string userdata = serializer.Serialize(user);
                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                        1,
                        user.UserName,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(15),
                        false,
                        userdata
                    );
                string encTicket = FormsAuthentication.Encrypt(authTicket);
                HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                Response.Cookies.Add(faCookie);
                return RedirectToAction("Index", "App");

            }
            //TODO: Handle denied (or canceled request)
            else
            {
                //Start authentication process with twitter
                return MessagingUtilities.AsActionResult(TwitterConsumer.StartSignInWithTwitter(true));
            }
        }
Beispiel #10
0
        public ActionResult LogOn(T_Manager model)
        {
            //判断是否Model是否有错误信息弹出,如果有错误为false 没则为true
            if (ModelState.IsValid)
            {
                T_Manager manager = manager_service.Login(model).FirstOrDefault();
                if (manager != null)
                {
                    //1.保存登陆名,如果设置了 [Authorize],则那些视图需要登陆成功后才能访问
                    //FormsAuthentication.SetAuthCookie(manager.mana_login_name.ToString(), false);

                    ////2.存储登陆名外,再添加角色权限
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                        1, // 版本号。 
                        manager.mana_id.ToString(), // 与身份验证票关联的用户ID。 
                        DateTime.Now, // Cookie 的发出时间。 
                        DateTime.Now.AddMinutes(15),// Cookie 的到期日期。 
                        false, // 如果 Cookie 是持久的,为 true;否则为 false。 
                        manager.mana_role.ToString());//将存储在 Cookie 中的用户定义数据。 
                    string encryptedTicket = FormsAuthentication.Encrypt(ticket);//加密
                    //存入Cookie 
                    HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                    Response.Cookies.Add(authCookie);

                    return RedirectToAction("Home", "Main");
                }
                else
                {
                    ViewBag.SubmitError = "账号密码错误";
                }
            }
            return View();
        }
        public ActionResult Login(LoginViewModel viewModel)
        {
            var apresentador = new LoginApresentador();
            var requisicao = new LoginRequisicao
            {
                Email = viewModel.Email,
                Senha = viewModel.Senha
            };

            this.loginExecutor.Apresentador = apresentador;
            this.loginExecutor.Executar(requisicao);

            if (apresentador.UsuarioExiste)
            {
                //create the authentication ticket
                var authTicket = new FormsAuthenticationTicket(
                  1,
                  viewModel.Email,  //user id
                  DateTime.Now,
                  DateTime.Now.AddMinutes(20),  // expiry
                  true,  //true to remember
                  "", //roles
                  "/"
                );

                //encrypt the ticket and add it to a cookie
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
                Response.Cookies.Add(cookie);
                return RedirectToAction("Index", "Blog");
            }

            return View();
        }
 public HttpResponseMessage Authenticate()
 {
     var credentials = Request.Content.ReadAsStringAsync().Result;
     var postData = JObject.Parse(credentials);
     var username = postData["Username"].ToString().Trim();
     var password = postData["Password"].ToString().Trim();
     var match = DynamoDBConnection.Instance.GetUser(username);
     if (match == null) {
         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Unrecognized username or password");
     }
     var data = JObject.Parse(match["UserInfo"]);
     var hashedPassword = data["Password"].ToString();
     bool authenticated;
     if (hashedPassword != "test") {
         byte[] charArray = hashedPassword.Select(i => (byte)i).ToArray();
         var passwordHash = new PasswordHash(charArray);
         authenticated = passwordHash.Verify(password);
     } else {
         authenticated = true;
     }
     if (authenticated) {
         var toReturn = new HttpResponseMessage(HttpStatusCode.OK);
         FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(username, true, 525600);
         var sessionKey = FormsAuthentication.Encrypt(ticket);
         toReturn.Headers.Add("Set-Cookie", string.Format("session_id={0}; Path=/", sessionKey));
         toReturn.Headers.Add("Set-Cookie", string.Format("user_id={0}; Path=/", username));
         toReturn.Content = new StringContent(sessionKey.ToString());
         return toReturn;
     } else {
         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Unrecognized username or password");
     }
 }
        protected void btnLogin_Click(object sender, EventArgs e)
        {
               Users _loginUser = _dal.VerifyPassword(txtUserName.Text, txtPassword.Text);

               if (_loginUser == null)
                   lblerror.Text = "Invalid Login";
               else
               {


                   UserData userData = new UserData
                   {
                       fullName = _loginUser.firstName,
                       userName = _loginUser.LoweredUserName,
                       userId = _loginUser.UserId
                   };
                   
 
                   string[] roles = new string[3];

                   if (_loginUser.canAdd == true)
                       roles[0] = "canAdd";
                   if (_loginUser.canDelete == true)
                       roles[1] = "canDelete";
                   if (_loginUser.canEdit == true)
                       roles[2] = "canEdit";

                   string _roles = String.Join(",", roles);

                   FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                     1,                                     // ticket version
                     _loginUser.UserName,                              // authenticated username
                     DateTime.Now,                          // issueDate
                     DateTime.Now.AddMinutes(30),           // expiryDate
                      true,                          // true to persist across browser sessions we want to be always for end user unless they log out.
                     _roles,                 // can be used to store additional user data
                     FormsAuthentication.FormsCookiePath);  // the path for the cookie

                   // Encrypt the ticket using the machine key
                   string encryptedTicket = FormsAuthentication.Encrypt(ticket);

                   // Add the cookie to the request to save it
                   HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                   cookie.HttpOnly = true;
                   Response.Cookies.Add(cookie);

                   lblerror.Text = "Success!";

                   // if its a player throw them into front end other wise fire them into the back end
                   if (_loginUser.accountType == Constants.playerGuid &&  _loginUser.accountType == Constants.adminGuid)
                   {
                       Response.Redirect("~/dashboard/dashboard.aspx");

                   }
                   else if (_loginUser.accountType == Constants.teamGuid && _loginUser.accountType == Constants.leagueGuid && _loginUser.accountType == Constants.clubGuid)
                   {
                       Response.Redirect("~/Backdoor/default.aspx");
                   }
               }
        }
        // helper to generate link [to the .ashx] containing channel name and (encoded) userName
        public static string GenerateChannelLink(string handlerPath, string channelName, string userName)
        {
            string link = VirtualPathUtility.ToAbsolute(handlerPath);

            if (string.IsNullOrEmpty(userName))
            {
                if (!string.IsNullOrEmpty(channelName))
                {
                    link += "?c=" + HttpUtility.UrlEncodeUnicode(channelName);
                }
            }
            else
            {
                if (channelName == null)
                {
                    channelName = string.Empty;
                }

                userName = "******" + userName; // not to confuse the encrypted string with real auth ticket for real user
                DateTime ticketDate = DateTime.Now.AddDays(-100); // already expried

                var t = new FormsAuthenticationTicket(2, userName, ticketDate, ticketDate.AddDays(2), false, channelName, "/");

                link += "?t=" + FormsAuthentication.Encrypt(t);
            }

            return link;
        }
Beispiel #15
0
        public CompilifyIdentity(FormsAuthenticationTicket authenticationTicket)
        {
            ticket = authenticationTicket;

            Guid id;
            userId = Guid.TryParse(ticket.UserData, out id) ? id : default(Guid);
        }
        public static void RedirectFromLogin(string login, IEnumerable<RestResponseCookie> cookies)
        {
            if (cookies == null)
                throw new ArgumentNullException("cookies");

            cookies = cookies.ToArray();

            var data = JsonConvert.SerializeObject(cookies.ToDictionary(c => c.Name, c => c.Value));

            var cookie = FormsAuthentication.GetAuthCookie(login, false);

            var sourceTicket = FormsAuthentication.Decrypt(cookie.Value);

            if (sourceTicket == null)
                throw new ApplicationException("Unable to decrypt authentication");

            var expiration = cookies.Select(c => c.Expires)
                                    .Where(exp => exp > DateTime.Today.AddYears(-1) && exp < DateTime.Today.AddYears(1))
                                    .Concat(new[] {sourceTicket.Expiration})
                                    .Min();

            var ticket = new FormsAuthenticationTicket(
                sourceTicket.Version, sourceTicket.Name, sourceTicket.IssueDate,
                expiration, false, data);

            cookie.Value = FormsAuthentication.Encrypt(ticket);

            Response.SetCookie(cookie);
            var redirectUrl = FormsAuthentication.GetRedirectUrl(login, sourceTicket.IsPersistent);
            Response.Redirect(redirectUrl);
        }
Beispiel #17
0
        public void SetLoginCookie(string userName, string password, bool isPermanentCookie)
        {
            if (_response != null)
            {
                if (isPermanentCookie)
                {
                    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, userName,
                        DateTime.Now, DateTime.MaxValue, true, password, FormsAuthentication.FormsCookiePath);

                    string encUserAuthTicket = FormsAuthentication.Encrypt(authTicket);
                    HttpCookie authUserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encUserAuthTicket);

                    if (authTicket.IsPersistent)
                    {
                        authUserCookie.Expires = authTicket.Expiration;
                    }
                    authUserCookie.Path = FormsAuthentication.FormsCookiePath;
                    _response.Cookies.Add(authUserCookie);
                }
                else
                {
                    FormsAuthentication.SetAuthCookie(userName, isPermanentCookie);
                }
            }
        }
Beispiel #18
0
        public bool ValidateUser( string username, string password)
        {
            Person user = Repository.Data.Get<Person>().Where(x => x.LoginName
                .Equals(username, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault().Value;

            if (user == null)
                return false;

            if (user.Validate(password) && user.Active)
            {
                var authenticationTicket = new FormsAuthenticationTicket
                    (1, username, DateTime.Now, DateTime.Now.AddMinutes(30), true, user.Id.ToString());

                string cookieContents = FormsAuthentication.Encrypt(authenticationTicket);

                var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
                {
                    Expires = authenticationTicket.Expiration,
                    Path = FormsAuthentication.FormsCookiePath
                };

                HttpContext.Current.Response.Cookies.Add(cookie);

                return true;
            }
            return false;
        }
Beispiel #19
0
        public virtual void SignIn(MembershipUser membershipUser, bool createPersistentCookie)
        {
            var now = DateTime.UtcNow.ToLocalTime();

            var ticket = new System.Web.Security.FormsAuthenticationTicket(
                1 /*version*/,
                membershipUser.Username,
                now,
                now.Add(_expirationTimeSpan),
                createPersistentCookie,
                membershipUser.Username,
                System.Web.Security.FormsAuthentication.FormsCookiePath);

            var encryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(ticket);

            var cookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, encryptedTicket);

            cookie.HttpOnly = true;
            if (ticket.IsPersistent)
            {
                cookie.Expires = ticket.Expiration;
            }
            cookie.Secure = System.Web.Security.FormsAuthentication.RequireSSL;
            cookie.Path   = System.Web.Security.FormsAuthentication.FormsCookiePath;
            if (System.Web.Security.FormsAuthentication.CookieDomain != null)
            {
                cookie.Domain = System.Web.Security.FormsAuthentication.CookieDomain;
            }

            _httpContext.Response.Cookies.Add(cookie);
            _cachedMembershipUser = membershipUser;
        }
Beispiel #20
0
        public void Application_PostAuthenticateRequest()
        {
            //ESTE METODO ENTRARA CUANDO HAYA CREADO EL TICKET
            //DEBEMOS RECUPERAR EL TICKET QUE ESTA EN LA COOKIE
            HttpCookie cookie = Request.Cookies["TICKETUSUARIO"];

            if (cookie != null)
            {
                //ESTAMOS EN EL SISTEMA (FACTOR UNO)
                //RECUPERAR EL TICKET DE LA COOKIE
                //NECESITAMOS LOS DATOS CIFRADOS
                String datoscifrados = cookie.Value;
                System.Web.Security.FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(datoscifrados);
                //HEMOS ALMACENADO EL USERNAME EN NAME
                //HEMOS ALMACENADO EL ROLE EN USERDATA
                String username = ticket.Name;
                String role     = ticket.UserData;
                //UN USUARIO NORMAL, ES UN GENERIC PRINCIPAL
                //UN PRINCIPAL ESTÁ COMPUESTO POR UNA IDENTIDAD (NAME) Y POR LOS ROLES[]
                GenericIdentity  identidad = new GenericIdentity(username);
                GenericPrincipal user      = new GenericPrincipal(identidad, new String[] { role });
                //HAY QUE PONER AL USUARIO EN LA SESSION DE LA APLICACION
                HttpContext.Current.User = user;
            }
        }
        private void OnPreSendRequestHeaders(object sender, EventArgs eventArgs)
        {
            var app = (HttpApplication)sender;

            try
            {
                var ctx = ContextRegistry.GetContext();
                var sessao = (Sessao)ctx.GetObject("Sessao");

                if (!sessao.IsAutenticado)
                {
                    FormsAuthentication.SignOut();
                    return;
                }

                var ticket = new FormsAuthenticationTicket(
                    1,
                    sessao.Usuario.UID.ToString(),
                    DateTime.Now,
                    DateTime.Now.AddMinutes(20),
                    false,
                    sessao.Organizacao.UID.ToString());

                var cookie = FormsAuthentication.GetAuthCookie(sessao.Usuario.UID.ToString(), false);
                cookie.Value = FormsAuthentication.Encrypt(ticket);
                app.Context.Response.SetCookie(cookie);

            }
            finally 
            {
                _log.Warn(app.Request.Path + " - " + app.Response.StatusCode);
            }
        }
Beispiel #22
0
        public ActionResult Login(LoginModel model)
        {
            var repository = new UsersRepository();
            var verify = repository.Login(model.Password, model.Username);

            try
            {
                if (verify)
                {
                    var ticket = new FormsAuthenticationTicket(1,
                                                           model.Username,
                                                           DateTime.Now,
                                                           DateTime.Now.AddSeconds(30),
                                                           model.Persistent,
                                                           "");

                    var strEncryptedTicket = FormsAuthentication.Encrypt(ticket);
                    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strEncryptedTicket);
                    Response.Cookies.Add(cookie);

                    return RedirectToAction(Actions.Index, HomeController.Name);
                }
            }
            catch (Exception)
            {

            }

            return View(Views.Login);
        }
        private static void CreateDefaultIdentityCookie(UserClaim userClaim)
        {
            var now = DateTime.Now;
            var claimJson = userClaim.ToJson();

            var ticket = new FormsAuthenticationTicket(1,
                                                       userClaim.Username,
                                                       now,
                                                       now.Add(FormsAuthentication.Timeout),
                                                       false,
                                                       claimJson,
                                                       FormsAuthentication.FormsCookiePath);

            // Encrypt the ticket.
            string encTicket = FormsAuthentication.Encrypt(ticket);

            // Create the cookie.
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
                         {
                             Domain = FormsAuthentication.CookieDomain,
                             HttpOnly = true,
                             Path = FormsAuthentication.FormsCookiePath
                         };

            HttpContext.Current.Response.Cookies.Add(cookie);
        }
Beispiel #24
0
        /// <summary>  
        /// 创建登录用户的票据信息  
        /// </summary>  
        /// <param name="strUserName"></param>  
        public static string CreateLoginUserTicket(string userId)
        {
            DateTime loginTime = DateTime.Now;//用户的登录时间
            //构造Form验证的票据信息
            ///把登录时间和用户ID写进Cookie中,后面可以用于判断用户的登录时间间隔
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userId, DateTime.Now, DateTime.Now.AddMinutes(90),
                true, string.Format("{0}:{1}", userId, loginTime), FormsAuthentication.FormsCookiePath);

            string ticString = FormsAuthentication.Encrypt(ticket);

            //把票据信息写入Cookie和Session
            //SetAuthCookie方法用于标识用户的Identity状态为true
            HttpContext.Current.Response.Cookies.Add(new HttpCookie("UserLoginCookieToken", ticString));
            FormsAuthentication.SetAuthCookie(userId, true);
            HttpContext.Current.Session["USER_LOGON_TICKET"] = ticString;

            //重写HttpContext中的用户身份,可以封装自定义角色数据;
            //判断是否合法用户,可以检查:HttpContext.User.Identity.IsAuthenticated的属性值
            string[] roles = ticket.UserData.Split(',');
            IIdentity identity = new FormsIdentity(ticket);
            IPrincipal principal = new GenericPrincipal(identity, roles);
            HttpContext.Current.User = principal;

            return ticString;//返回票据
        }
Beispiel #25
0
        public ActionResult Index(LoginViewModel login)
        {
            if (!ModelState.IsValid) return View();

            if (!userRepo.ValidateUser(login))
            {
                ModelState.AddModelError("", "Incorrect username or password");

                return View();
            }

            var authTicket = new FormsAuthenticationTicket(
                    1,
                    login.UserName,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(20),  // expiry
                    login.RememberMe,
                    "", //roles
                    "/"
            );

            //encrypt the ticket and add it to a cookie
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
            Response.Cookies.Add(cookie);

            return Redirect("UserHome");
        }
        public ActionResult Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                var currentUser = clientService.GetClientByLoginAndPassword(model.Login, model.Password);

                if(currentUser != null)
                {
                    string name;
                    if (currentUser.FirstName != null)
                        name = currentUser.FirstName + " " + currentUser.LastName;
                    name = currentUser.Login;

                    var authTicket = new FormsAuthenticationTicket(
                        1,
                        currentUser.UserId.ToString(),
                        DateTime.Now,
                        DateTime.Now.AddMinutes(60),
                        true,
                        name
                        );

                    string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                    var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                    HttpContext.Response.Cookies.Add(authCookie);
                    return RedirectToAction("Index", "Home");
                }
            }
            return View(model);
        }
        public ActionResult Index(BiscuitChief.Models.Login login, string ReturnUrl = "")
        {
            if (ModelState.IsValid)
            {

                bool isvalidlogin = Models.Login.ValidateLogin(login.UserName, login.Password);

                if (isvalidlogin)
                {
                    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, login.UserName, DateTime.Now, DateTime.Now.AddMinutes(30), true, "");
                    String cookiecontents = FormsAuthentication.Encrypt(authTicket);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookiecontents) { Expires = authTicket.Expiration, Path = FormsAuthentication.FormsCookiePath };
                    Response.Cookies.Add(cookie);

                    if (!String.IsNullOrEmpty(ReturnUrl))
                    { return Redirect(ReturnUrl); }
                    else
                    { return Redirect("/"); }
                }
                else
                {
                    FormsAuthentication.SignOut();
                    Session.Clear();
                }
            }

            return View(login);
        }
Beispiel #28
0
        private void GenerateAuthenticationCookie(int expiryInMinutes, Guid userGuid)
        {
            DateTime cookieExpiration = DateTime.Now.AddMinutes(expiryInMinutes); // change to months for production
            var authenticationTicket =
                new FormsAuthenticationTicket(
                    2,
                    userGuid.ToString(),
                    DateTime.Now,
                    cookieExpiration,
                    true,
                    string.Empty,
                    FormsAuthentication.FormsCookiePath);

            // ticket must be encrypted
            string encryptedTicket = FormsAuthentication.Encrypt(authenticationTicket);

            // create cookie to contain encrypted auth ticket
            var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            authCookie.Expires = authenticationTicket.Expiration;
            authCookie.Path = FormsAuthentication.FormsCookiePath;

            // clear out existing cookie for good measure (probably overkill) then add
            HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            HttpContext.Current.Response.Cookies.Add(authCookie);
        }
Beispiel #29
0
        public bool SingIn(Customer cusomer)
        {
            var now = DateTime.UtcNow.ToLocalTime();
            var ticket = new FormsAuthenticationTicket(
                1 /*version*/,
                cusomer.UserName,
                now,
                now.Add(TimeSpan.FromMinutes(1)),
                false,
                cusomer.UserName,
                FormsAuthentication.FormsCookiePath);

            var encryptedTicket = FormsAuthentication.Encrypt(ticket);

            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            cookie.HttpOnly = true;
            if (ticket.IsPersistent)
            {
                cookie.Expires = ticket.Expiration;
            }
            cookie.Secure = FormsAuthentication.RequireSSL;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            if (FormsAuthentication.CookieDomain != null)
            {
                cookie.Domain = FormsAuthentication.CookieDomain;
            }
            HttpContext.Current.Response.Cookies.Add(cookie);
            cacheCustomer = cusomer;
            return true;
        }
        public bool Authenticate(string username, string password)
        {
            _userContext = _clientDataAccess.LogIn(username, ClassLib.DataStructures.HashClass.CreateFirstHash(password, username));

            if (_userContext != null)
            {
                const int timeout = 60;
                var ticket = new FormsAuthenticationTicket(
                    1,
                    username,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(timeout),
                    true,
                    _userContext.Id.ToString()
                    );
                var encrypted = FormsAuthentication.Encrypt(ticket);
                var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);

                HttpContext.Current.Response.Cookies.Add(cookie);

                _authenticationCookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);

                return true;
            }

            return false;
        }
        public ActionResult Index(UserModel User)
        {
            if (User.IsValid(User.UserName, User.Password))
                {
                    var userEntity = _db.User.ToList();

                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                                                                1,
                                                                User.UserName,
                                                                DateTime.Now,
                                                                DateTime.Now.AddMinutes(10),
                                                                false,
                                                                null);

                    string encryptedTicket = FormsAuthentication.Encrypt(ticket);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                    cookie["userName"] = User.UserName;
                    this.Response.Cookies.Add(cookie);
                    return RedirectToAction("Feed", "Feed");
                }
                else
                {
                    ModelState.AddModelError("", "Login data is incorrect!");
                }
            //}
            return View(User);
        }
Beispiel #32
0
        public UserIdentity(System.Web.Security.FormsAuthenticationTicket ticket)
        {
            string[] a = ticket.UserData.Split('|');
            Name = ticket.Name;

            // WebIdentity Variables
            CustomerID = int.Parse(GlobalUtilities.Coalesce(a[0], "0"));
            FirstName  = GlobalUtilities.Coalesce(a[1], "");
            LastName   = GlobalUtilities.Coalesce(a[2], "");
            Company    = GlobalUtilities.Coalesce(a[3], "");
            Country    = GlobalUtilities.Coalesce(a[4], "");

            EnrollerID = Convert.ToInt32(a[5]);
            SponsorID  = Convert.ToInt32(a[6]);

            LanguageID         = int.Parse(GlobalUtilities.Coalesce(a[7], Languages.English.ToString()));
            CustomerTypeID     = int.Parse(GlobalUtilities.Coalesce(a[8], CustomerTypes.Distributor.ToString()));
            CustomerStatusID   = int.Parse(GlobalUtilities.Coalesce(a[9], CustomerStatusTypes.Active.ToString()));
            DefaultWarehouseID = int.Parse(GlobalUtilities.Coalesce(a[10], Warehouses.Default.ToString()));
            PriceTypeID        = int.Parse(GlobalUtilities.Coalesce(a[11], PriceTypes.Distributor.ToString()));
            CurrencyCode       = GlobalUtilities.Coalesce(a[12], "usd");
            CreatedDate        = Convert.ToDateTime(a[13]);

            Expires = ticket.Expiration;
        }
        public static void AuthenticateUser(string userName, int userId, string firstName, bool createPersistenctCookie)
        {
            try
            {
                var userData = new WarehouseManagementUserData()
                {
                    UserId = userId,
                    UserName = userName,
                    FirstName = firstName
                };

                var userDataString = WarehouseManagementUserData.Serialize(userData);
                var authCookie = FormsAuthentication.GetAuthCookie(userName, createPersistenctCookie);

                var ticket = FormsAuthentication.Decrypt(authCookie.Value);
                var extendedTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userDataString);

                authCookie.Value = FormsAuthentication.Encrypt(extendedTicket);

                HttpContext.Current.Response.Cookies.Add(authCookie);
            }
            catch (Exception e)
            {
                throw new ProviderException(string.Format("Failed to authenticate user {0}.", userName), e);
            }
        }
Beispiel #34
0
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var login = model.Login;
                var passwordHash = _cryptoProvider.GetHash(model.Password, Salt);

                var userEntity =
                    _dContext.Users.FirstOrDefault(x => x.Login == login && x.PasswordHash == passwordHash);

                if (userEntity != null)
                {
                    var authTicket = new FormsAuthenticationTicket(
                        1,
                        login,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(20),
                        true,
                        userEntity.UserRole.ToString()
                        );
                    string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                    var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                    System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
                    return RedirectToAction("Index", "Admin");
                }
                else
                {
                    ModelState.AddModelError("", "The user login or password provided is incorrect.");
                }
            }
            return View(model);
        }
Beispiel #35
0
        public UserIdentity(System.Web.Security.FormsAuthenticationTicket ticket)
        {
            Name    = ticket.Name;
            Expires = ticket.Expiration;

            // Populate this object with the properties
            DeserializeProperties(ticket.UserData);
        }
Beispiel #36
0
        /// <summary>
        /// 1.0 将字符串加密
        /// </summary>
        /// <param name="strOri"></param>
        /// <returns></returns>
        public static string ToEncyptFormsAuthenticationString(this string strOri)
        {
            //1.创建 授权票据对象,将 要加密的字符串 传入
            FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(1, "aa", DateTime.Now, DateTime.Now.AddMinutes(60), true, strOri);

            //2.调用加密方法,将票据 转成 加密字符串返回
            return(FormsAuthentication.Encrypt(ticket));
        }
        /// <summary>
        /// encrypting string
        /// </summary>
        /// <returns></returns>
        public static string Encrypt(string Password)
        {
            string str = "";
            FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(Password, true, 2);

            str = FormsAuthentication.Encrypt(ticket).ToString();
            return(str);
        }
Beispiel #38
0
        private void WriteCookie(ManagerInfo userToLogin)
        {
            RoleInfo role = ManagerHelper.GetRole(userToLogin.RoleId);

            System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(1, userToLogin.UserId.ToString(), System.DateTime.Now, System.DateTime.Now.AddDays(1.0), true, string.Format("{0}_{1}", role.RoleId, role.IsDefault));
            string value = System.Web.Security.FormsAuthentication.Encrypt(ticket);

            System.Web.HttpCookie cookie = new System.Web.HttpCookie(string.Format("{0}{1}", Globals.DomainName, System.Web.Security.FormsAuthentication.FormsCookieName), value);
            System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
        }
        protected void BtnLogin_Click(object sender, EventArgs e)
        {
            ZXPUserData zxpUD = GetLoginCredentials();

            try
            {
                if (zxpUD._uid > 0)
                {
                    AuditLog aLog = new AuditLog(zxpUD._uid);
                    aLog.createNewAuditLogEntry(aLog);

                    string strUserData = zxpUD.SerializeZXPUserData(zxpUD);

                    System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(1, LoginControl.UserName, DateTime.Now, DateTime.Now.AddDays(5), LoginControl.RememberMeSet, strUserData);
                    string enticket = System.Web.Security.FormsAuthentication.Encrypt(ticket);
                    System.Web.HttpCookie authcookie = new System.Web.HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, enticket);
                    if (ticket.IsPersistent)
                    {
                        authcookie.Expires = ticket.Expiration;
                    }
                    Response.Cookies.Add(authcookie);


                    string logMsg = string.Concat("btnLogin_click : ", zxpUD._UserName, " cookie: ", authcookie.Value.ToString());
                    ErrorLogging.WriteEvent(logMsg, EventLogEntryType.Information);

                    string pageURL = System.Web.Security.FormsAuthentication.GetRedirectUrl(LoginControl.UserName, LoginControl.RememberMeSet);
                    Response.Redirect(pageURL);

                    // Response.Redirect(pageURL, false);
                    // Context.ApplicationInstance.CompleteRequest(); // end response
                }
                else
                {
                    string ErrorText = "Login failed. Please check your Username and Password and try again.";
                    string pageURL   = Request.Url.AbsolutePath + "?ErrorText=" + ErrorText;
                    Response.Redirect(pageURL);
                    // Response.Redirect(pageURL, false);
                    //Context.ApplicationInstance.CompleteRequest(); // end response
                }
            }
            catch (System.Threading.ThreadAbortException ex)
            {
                ex.ToString();
                //do nothing - caused by response.redirect
            }
            catch (Exception ex)
            {
                string strErr = " Exception Error in Login BtnLogin_Click(). Details: " + ex.ToString();
                ErrorLogging.WriteEvent(strErr, EventLogEntryType.Error);
                System.Web.HttpContext.Current.Session["ErrorNum"] = 1;
                ErrorLogging.sendtoErrorPage(1);
            }
        }
Beispiel #40
0
        public ActionResult Index()
        {
            var a = "";

            if (HttpContext.User != null && HttpContext.User.Identity is FormsIdentity)
            {
                var b = "";
            }


            var id = (System.Web.Security.FormsIdentity)User.Identity;

            System.Web.Security.FormsAuthenticationTicket ticket = id.Ticket;

            return(View());
        }
Beispiel #41
0
        public void addLoginedCookie(Model.User mdl)
        {
            System.Web.Security.FormsAuthentication.SignOut();

            HttpCookie authCookie = System.Web.Security.FormsAuthentication.GetAuthCookie(mdl.UserName, true);

            System.Web.Security.FormsAuthenticationTicket ticket = System.Web.Security.FormsAuthentication.Decrypt(authCookie.Value);

            string userData = mdl.UserName;

            System.Web.Security.FormsAuthenticationTicket newTicket = new System.Web.Security.FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData, System.Web.Security.FormsAuthentication.FormsCookiePath);

            authCookie.Value = System.Web.Security.FormsAuthentication.Encrypt(newTicket);

            Response.Cookies.Add(authCookie);
        }
Beispiel #42
0
    //protected void btnOk_Click(object sender, EventArgs e)
    //{
    //    Login();
    //}

    //protected void txtPassword_TextChanged(object sender, EventArgs e)
    //{
    //    Login();
    //}

    private void Login()
    {
        //t_Users dbUser = _userBL.GetUser(txtUsername.Text);
        t_Users dbUser = _userBL.GetUser(Login1.UserName);

        if (dbUser == null)
        {
            //ntf.VisibleOnPageLoad = true;
            //ntf.Text = "Sai ký danh hoặc mật khẩu.";
            //txtUsername.Focus();
            return;
        }
        //string hashedPassword = _stringUT.HashMD5(_stringUT.HashMD5(txtPassword.Text) + dbUser.Salt);
        string hashedPassword = _stringUT.HashMD5(_stringUT.HashMD5(Login1.Password) + dbUser.Salt);

        if (string.Equals(hashedPassword, dbUser.Password))
        {
            HttpCookie cookie;
            System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(1, dbUser.Username, DateTime.Now,
                                                                                                                     DateTime.Now.AddMinutes(HttpContext.Current.Session.Timeout),
                                                                                                                     true, dbUser.Role + "|" + dbUser.ConsumerId, System.Web.Security.FormsAuthentication.FormsCookiePath);
            string hashCookie = System.Web.Security.FormsAuthentication.Encrypt(ticket);
            cookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, hashCookie);
            Response.Cookies.Add(cookie);
            t_Users user = new t_Users();
            user           = dbUser;
            user.LoginTime = user.LoginTime == null ? 0 : user.LoginTime + 1;
            _userBL.UpdateUser(user, dbUser);
            if (dbUser.Role != "consumer" && dbUser.Role != "staff")
            {
                Response.Redirect("~/Supervisor/Logger/MapJS_rev1.aspx?uid=" + user.Username);
            }
            else
            {
                Response.Redirect("~/Consumer/Logger/MapJS_rev1.aspx?uid=" + user.Username);
            }
        }
        else
        {
            //ntf.VisibleOnPageLoad = true;
            //ntf.Text = "Sai ký danh hoặc mật khẩu.";
            //txtUsername.Focus();

            TextBox TextBoxUserName = Login1.FindControl("UserName") as TextBox;
            TextBoxUserName.Focus();
        }
    }
Beispiel #43
0
        public SiteIdentity(System.Web.Security.FormsAuthenticationTicket authTicket, HttpCookie infoCookie)
        {
            permissions = new ArrayList();
            string[] permArray = authTicket.UserData.Split('|');
            foreach (string p in permArray)
            {
                permissions.Add(p);
            }

            userId       = Convert.ToInt32(authTicket.Name);
            created      = authTicket.IssueDate;
            expires      = authTicket.Expiration;
            isExpired    = authTicket.Expired;
            isPersistent = authTicket.IsPersistent;
            firstName    = infoCookie.Values["FirstName"];
            lastName     = infoCookie.Values["LastName"];
        }
Beispiel #44
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public string GetUserRolesFromTicket()
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            System.Web.Security.FormsAuthenticationTicket ticket = System.Web.Security.FormsAuthentication.Decrypt(context.Request.Cookies[FormsAuthentication.FormsCookieName].Value);

            string userRoles = string.Empty;

            foreach (String role in ticket.UserData.Split(new char[] { ';' }))
            {
                if (role.Length > 0)
                {
                    userRoles += "'" + role + "',";
                }
            }

            return(userRoles.Substring(0, (userRoles.Length - 1)));
        }
Beispiel #45
0
        protected void Application_BeginRequest()
        {
            if (HttpContext.Current.Request.FilePath.Contains("Components/DownLoads/"))
            {
                HttpCookie Cookie = Context.Request.Cookies[System.Web.Security.FormsAuthentication.FormsCookieName];

                if (Cookie != null)
                {
                    System.Web.Security.FormsAuthenticationTicket authTicket = null;
                    authTicket = System.Web.Security.FormsAuthentication.Decrypt(Cookie.Value);
                    if (authTicket.Name != "")
                    {
                        mysourceblogrepository.strclickPlus(HttpContext.Current.Request.FilePath);
                    }
                }
            }
        }
Beispiel #46
0
        void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpContext     ctx = app.Context; //获取本次Http请求的HttpContext对象

            if (ctx.User != null)
            {
                if (ctx.Request.IsAuthenticated == true) //验证过的一般用户才能进行角色验证
                {
                    System.Web.Security.FormsIdentity             fi     = (System.Web.Security.FormsIdentity)ctx.User.Identity;
                    System.Web.Security.FormsAuthenticationTicket ticket = fi.Ticket;     //取得身份验证票
                    string   userData = ticket.UserData;                                  //从UserData中恢复role信息
                    string[] roles    = userData.Split(',');                              //将角色数据转成字符串数组,得到相关的角色信息
                    ctx.User = new System.Security.Principal.GenericPrincipal(fi, roles); //这样当前用户就拥有角色信息了
                }
            }
        }
Beispiel #47
0
 void Application_AuthenticateRequest(object sender, EventArgs e)
 {
     try
     {
         if (Request.IsAuthenticated == true)
         {
             FormsIdentity id = (System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity;
             System.Web.Security.FormsAuthenticationTicket ticket = id.Ticket;
             string   userData = ticket.UserData;
             string[] arrStr   = userData.Split(new Char[] { ';' });
             HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, arrStr);
         }
     }
     catch (Exception)
     {
         // ExceptionManager.HandleException("Error", ex, "Application_AuthenticateRequest", -1);
     }
 }
        public ActionResult Login(UserLogin login, string ReturnUrl)
        {
            string message = "";

            using (WypAutEntities dc = new WypAutEntities())
            {
                var v = dc.Users.Where(a => a.Email == login.Email).FirstOrDefault();
                if (v != null)
                {
                    if (string.Compare(Crypto.Hash(login.Password), v.Password) == 0)
                    {
                        int    timeout   = login.RememberMe ? 525600 : 20; // 525600min = 1 year
                        var    ticket    = new System.Web.Security.FormsAuthenticationTicket(login.Email, login.RememberMe, timeout);
                        string encrypted = FormsAuthentication.Encrypt(ticket);
                        var    cookie    = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
                        cookie.Expires  = DateTime.Now.AddMinutes(timeout);
                        cookie.HttpOnly = true;
                        Response.Cookies.Add(cookie);

                        if (Url.IsLocalUrl(ReturnUrl))
                        {
                            return(Redirect(ReturnUrl));
                        }
                        else
                        {
                            return(RedirectToAction("Index", "Home"));
                        }
                    }
                    else
                    {
                        message = "Błędne hasło";
                    }
                }
                else
                {
                    message = "Błędny Email";
                }
            }
            ViewBag.Message = message;
            return(View());
        }
Beispiel #49
0
        public ActionResult Index(Login_VM model)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "請輸入帳號密碼。");
                return(View(model));
            }

            LoginLogic _user = new LoginLogic();


            if (_user.GetT(model) == null)
            {
                ModelState.AddModelError("", "無效的帳號或密碼。");
                return(View(model));
            }

            var ticket = new System.Web.Security.FormsAuthenticationTicket(
                version: 1,
                name: _user.User.ToString(),                //可以放使用者Id
                issueDate: DateTime.UtcNow,                 //現在UTC時間
                expiration: DateTime.UtcNow.AddMinutes(30), //Cookie有效時間=現在時間往後+30分鐘
                isPersistent: true,                         // 是否要記住我 true or false
                userData: _user.Name,                       //可以放使用者角色名稱

                cookiePath: FormsAuthentication.FormsCookiePath);

            var encryptedTicket = FormsAuthentication.Encrypt(ticket); //把驗證的表單加密
            var cookie          = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

            Response.Cookies.Add(cookie);

            //Session["username"] = _user.Name.ToString();

            return(RedirectToAction("Index", "Workout"));
        }
Beispiel #50
0
        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        // Encrypt a ticket

        /// <devdoc>
        ///    Given a FormsAuthenticationTicket, this
        ///    method produces a string containing an encrypted authentication ticket suitable
        ///    for use in an HTTP cookie.
        /// </devdoc>
        public static String Encrypt(FormsAuthenticationTicket ticket)
        {
            return(Encrypt(ticket, true));
        }
        public ActionResult LogOn(LogOnModel model)
        {
            CC.Data.MembershipUser membershipUser = null;
            if (ModelState.IsValid)
            {
                var context = this.db;
                //get membership user with the same username
                membershipUser = context.MembershipUsers
                                 .Include(f => f.User)
                                 .SingleOrDefault(f => f.LoweredUserName == model.UserName);

                //validate password if the user exists
                if (membershipUser == null)
                {
                    var u = context.Users.SingleOrDefault(f => f.UserName == model.UserName);
                    if (u != null)
                    {
                        var mu = context.MembershipUsers.SingleOrDefault(f => f.Id == u.Id);
                        log.Debug(string.Format("LogOn failed: membershipUser is null, user not null. The user's username is {0}, the username of membershipUser with same id is {1}",
                                                u.UserName, mu.LoweredUserName));
                    }
                    else
                    {
                        log.Debug(string.Format("LogOn failed: user wasn't found. The entered username is {0}", model.UserName));
                    }
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
                else if (membershipUser != null && membershipUser.ValidatePassword(model.Password))
                {
                    if (membershipUser.User.Disabled)
                    {
                        ModelState.AddModelError("", "This ID has been disabled due to inactivity.  If you wish to have this ID re-enabled, please contact your local administrator or your Claims Conference Program Assistant.");
                    }
                    else if (membershipUser.ExpirationDate > DateTime.Now)
                    {
                        ModelState.AddModelError("", "Account is expired");
                    }
                    else
                    {
                        //set authentication cookie
                        var user = membershipUser.User;

                        membershipUser.FailedPasswordAttemptCount = 0;
                        membershipUser.LastLoginDate = DateTime.Now;
                        context.SaveChanges();
                    }
                    if (!(FixedRoles.DafEvaluator | FixedRoles.DafReviewer | FixedRoles.AgencyUserAndReviewer | FixedRoles.SerAndReviewer).HasFlag((FixedRoles)membershipUser.User.RoleId))
                    {
                        ModelState.AddModelError(string.Empty, "Only DAF Evaluators and Reviewers are allowed to logon.");
                    }
                }
                else
                {
                    //if user inserted incorrect password less then 5 times and he is not disabled
                    if (membershipUser.FailedPasswordAttemptCount < 4 && !membershipUser.User.Disabled)
                    {
                        membershipUser.FailedPasswordAttemptCount++;
                        ModelState.AddModelError("", "The user name or password provided is incorrect.");
                    }
                    //user inserted incorrect password on his 5th time, or he is already disabled
                    else
                    {
                        membershipUser.User.Disabled = true;
                        ModelState.AddModelError("", "You have exceeded the number of failed login attempts allowed and your account has been locked. Please contact your Program Assistant or Program Officer for assistance.");
                    }
                    context.SaveChanges();
                }
            }

            if (ModelState.IsValid && membershipUser != null)
            {
                var oneWeek = 10080;                //one week
                var ticket  = new System.Web.Security.FormsAuthenticationTicket(membershipUser.User.UserName, true, oneWeek);

                var encryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(ticket);
                return(this.MyJsonResult(new
                {
                    username = membershipUser.User.UserName,
                    firstName = membershipUser.User.FirstName,
                    lastName = membershipUser.User.LastName,
                    roleId = membershipUser.User.RoleId,
                    agency = new {
                        id = membershipUser.User.Agency.Id,
                        name = membershipUser.User.Agency.Name
                    },
                    ticket = encryptedTicket
                }));
            }
            else
            {
                var data = ModelState.Where(f => f.Value.Errors.Any())
                           .SelectMany(f => f.Value.Errors)
                           .Select(f => f.ErrorMessage)
                           .ToList();
                return(this.MyJsonResult(new
                {
                    errors = data
                }, 400));
            }
        }
Beispiel #52
0
        /// <summary>
        /// encrypting string
        /// </summary>
        /// <param name="str">before encrypt string</param>
        /// <returns></returns>
        public static string Encrypt(string str)
        {
            FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(str, true, 2);

            return(FormsAuthentication.Encrypt(ticket).ToString());
        }
        public string Signup(AccountSignup data)
        {
            if (string.IsNullOrWhiteSpace(data.Firstname))
            {
                return("First name is required");
            }
            if (string.IsNullOrWhiteSpace(data.Lastname))
            {
                return("Last name is required");
            }

            if (string.IsNullOrWhiteSpace(data.Email))
            {
                return("Email is required");
            }
            if (!Regex.IsMatch(data.Email, @"^\S+@\S+\.\S+$"))
            {
                return("Unrecognized email address");
            }

            if (data.BirthDate > DateTime.Today.AddYears(-14))
            {
                return("Applicants must be 14 years or older");
            }
            if (data.BirthDate < DateTime.Today.AddYears(-120))
            {
                return("Invalid birthdate");
            }

            if (!(new[] { "m", "f", null }.Contains(data.Gender)))
            {
                return("Invalid gender");
            }

            if (data.Units.Length == 0)
            {
                return("Must select at least one unit");
            }

            if (string.IsNullOrWhiteSpace(data.Username))
            {
                return("Username is required");
            }
            if (data.Username.Length < 3)
            {
                return("Username must be 3 or more characters");
            }
            if (data.Username.Length > 200)
            {
                return("Username must be less than 200 characters");
            }
            if (!Regex.IsMatch(data.Username, @"^[a-zA-Z0-9\.\-_]+$"))
            {
                return("Username can only contain numbers, letters, and the characters '.', '-', and '_'");
            }
            if (membership.GetUser(data.Username, false) != null)
            {
                return("Username is already taken");
            }


            if (string.IsNullOrWhiteSpace(data.Password))
            {
                return("Password is required");
            }
            if (data.Password.Length < 6)
            {
                return("Password must be at least 6 characters");
            }
            if (data.Password.Length > 64)
            {
                return("Password must be less than 64 characters");
            }


            MembershipCreateStatus status;
            var user = membership.CreateUser(data.Username, data.Password, data.Email, null, null, false, null, out status);

            if (status != MembershipCreateStatus.Success)
            {
                return("Could not create user");
            }

            try
            {
                System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(data.Username, false, 5);
                Thread.CurrentPrincipal = new System.Web.Security.RolePrincipal(new System.Web.Security.FormsIdentity(ticket));

                Member newMember = new Member
                {
                    FirstName      = data.Firstname,
                    MiddleName     = data.Middlename,
                    LastName       = data.Lastname,
                    BirthDate      = data.BirthDate,
                    InternalGender = data.Gender,
                    Status         = MemberStatus.Applicant,
                    Username       = data.Username
                };
                db.Members.Add(newMember);

                PersonContact email = new PersonContact
                {
                    Person   = newMember,
                    Type     = "email",
                    Value    = data.Email,
                    Priority = 0
                };
                db.PersonContact.Add(email);

                foreach (Guid unitId in data.Units)
                {
                    UnitsController.RegisterApplication(db, unitId, newMember);
                }

                SarMembership.KcsarUserProfile profile = ProfileBase.Create(data.Username) as SarMembership.KcsarUserProfile;
                if (profile != null)
                {
                    profile.FirstName = data.Firstname;
                    profile.LastName  = data.Lastname;
                    profile.LinkKey   = newMember.Id.ToString();
                    profile.Save();
                }

                if (!System.Web.Security.Roles.RoleExists(APPLICANT_ROLE))
                {
                    System.Web.Security.Roles.CreateRole(APPLICANT_ROLE);
                }
                System.Web.Security.Roles.AddUserToRole(data.Username, APPLICANT_ROLE);

                string mailSubject  = string.Format("{0} account verification", ConfigurationManager.AppSettings["dbNameShort"] ?? "KCSARA");
                string mailTemplate = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Templates", "Email", "new-account-verification.html"));
                string mailBody     = mailTemplate
                                      .Replace("%Username%", data.Username)
                                      .Replace("%VerifyLink%", new Uri(this.Request.RequestUri, Url.Route("Default", new { httproute = "", controller = "Account", action = "Verify", id = data.Username })).AbsoluteUri + "?key=" + user.ProviderUserKey.ToString())
                                      .Replace("%WebsiteContact%", "*****@*****.**");

                db.SaveChanges();
                EmailService.SendMail(data.Email, mailSubject, mailBody);
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
                membership.DeleteUser(data.Username, true);
                return("An error occured while creating your user account");
            }

            return("OK");
        }
Beispiel #54
0
        internal static String Encrypt(FormsAuthenticationTicket ticket, bool hexEncodedTicket)
        {
            if (ticket == null)
            {
                throw new ArgumentNullException("ticket");
            }

            Initialize();
            //////////////////////////////////////////////////////////////////////
            // Step 1a: Make it into a binary blob
            byte[] bBlob = MakeTicketIntoBinaryBlob(ticket);
            if (bBlob == null)
            {
                return(null);
            }

            //////////////////////////////////////////////////////////////////////
            // Step 1b: If new crypto routines are enabled, call them instead.
            if (AspNetCryptoServiceProvider.Instance.IsDefaultProvider)
            {
                ICryptoService cryptoService = AspNetCryptoServiceProvider.Instance.GetCryptoService(Purpose.FormsAuthentication_Ticket);
                byte[]         protectedData = cryptoService.Protect(bBlob);
                bBlob = protectedData;
            }
            else
            {
#pragma warning disable 618 // calling obsolete methods
                // otherwise..

                //////////////////////////////////////////////////////////////////////
                // Step 2: Get the MAC and add to the blob
                if (_Protection == FormsProtectionEnum.All || _Protection == FormsProtectionEnum.Validation)
                {
                    byte[] bMac = MachineKeySection.HashData(bBlob, null, 0, bBlob.Length);
                    if (bMac == null)
                    {
                        return(null);
                    }
                    byte[] bAll = new byte[bMac.Length + bBlob.Length];
                    Buffer.BlockCopy(bBlob, 0, bAll, 0, bBlob.Length);
                    Buffer.BlockCopy(bMac, 0, bAll, bBlob.Length, bMac.Length);
                    bBlob = bAll;
                }

                if (_Protection == FormsProtectionEnum.All || _Protection == FormsProtectionEnum.Encryption)
                {
                    //////////////////////////////////////////////////////////////////////
                    // Step 3: Do the actual encryption
                    // DevDiv Bugs 137864: Include a random IV if under the right compat mode
                    // for improved encryption semantics
                    bBlob = MachineKeySection.EncryptOrDecryptData(true, bBlob, null, 0, bBlob.Length, false, false, IVType.Random);
                }
#pragma warning restore 618 // calling obsolete methods
            }

            if (!hexEncodedTicket)
            {
                return(HttpServerUtility.UrlTokenEncode(bBlob));
            }
            else
            {
                return(CryptoUtil.BinaryToHex(bBlob));
            }
        }
Beispiel #55
0
        ////////////////////////////////////////////////////////////
        // OnAuthenticate: Forms Authentication modules can override
        //             this method to create a Forms IPrincipal object from
        //             a WindowsIdentity
        private void OnAuthenticate(FormsAuthenticationEventArgs e)
        {
            HttpCookie cookie = null;

            ////////////////////////////////////////////////////////////
            // Step 1: If there are event handlers, invoke the handlers
            if (_eventHandler != null)
            {
                _eventHandler(this, e);
            }

            ////////////////////////////////////////////////////////////
            // Step 2: Check if the event handler created a user-object
            if (e.Context.User != null)
            {
                // do nothing because someone else authenticated
                return;
            }

            if (e.User != null)
            {
                // the event handler created a user
                e.Context.SetPrincipalNoDemand(e.User);
                return;
            }

            ////////////////////////////////////////////////////////////
            // Step 3: Extract the cookie and create a ticket from it
            bool cookielessTicket            = false;
            FormsAuthenticationTicket ticket = ExtractTicketFromCookie(e.Context, FormsAuthentication.FormsCookieName, out cookielessTicket);

            ////////////////////////////////////////////////////////////
            // Step 4: See if the ticket was created: No => exit immediately
            if (ticket == null || ticket.Expired)
            {
                return;
            }

            ////////////////////////////////////////////////////////////
            // Step 5: Renew the ticket
            FormsAuthenticationTicket ticket2 = ticket;

            if (FormsAuthentication.SlidingExpiration)
            {
                ticket2 = FormsAuthentication.RenewTicketIfOld(ticket);
            }

            ////////////////////////////////////////////////////////////
            // Step 6: Create a user object for the ticket
            e.Context.SetPrincipalNoDemand(new GenericPrincipal(new FormsIdentity(ticket2), new String[0]));

            ////////////////////////////////////////////////////////////
            // Step 7: Browser does not send us the correct cookie-path
            //         Update the cookie to show the correct path
            if (!cookielessTicket && !ticket2.CookiePath.Equals("/"))
            {
                cookie = e.Context.Request.Cookies[FormsAuthentication.FormsCookieName];
                if (cookie != null)
                {
                    cookie.Path = ticket2.CookiePath;
                }
            }

            ////////////////////////////////////////////////////////////
            // Step 8: If the ticket was renewed, save the ticket in the cookie
            if (ticket2 != ticket)
            {
                if (cookielessTicket && ticket2.CookiePath != "/" && ticket2.CookiePath.Length > 1)
                {
                    FormsAuthenticationTicket tempTicket = FormsAuthenticationTicket.FromUtc(ticket2.Version, ticket2.Name, ticket2.IssueDateUtc,
                                                                                             ticket2.ExpirationUtc, ticket2.IsPersistent, ticket2.UserData,
                                                                                             "/");
                    ticket2 = tempTicket;
                }
                String strEnc = FormsAuthentication.Encrypt(ticket2, !cookielessTicket);

                if (cookielessTicket)
                {
                    e.Context.CookielessHelper.SetCookieValue('F', strEnc);
                    e.Context.Response.Redirect(e.Context.Request.RawUrl);
                }
                else
                {
                    if (cookie != null)
                    {
                        cookie = e.Context.Request.Cookies[FormsAuthentication.FormsCookieName];
                    }

                    if (cookie == null)
                    {
                        cookie      = new HttpCookie(FormsAuthentication.FormsCookieName, strEnc);
                        cookie.Path = ticket2.CookiePath;
                    }

                    if (ticket2.IsPersistent)
                    {
                        cookie.Expires = ticket2.Expiration;
                    }
                    cookie.Value    = strEnc;
                    cookie.Secure   = FormsAuthentication.RequireSSL;
                    cookie.HttpOnly = true;
                    if (FormsAuthentication.CookieDomain != null)
                    {
                        cookie.Domain = FormsAuthentication.CookieDomain;
                    }
                    e.Context.Response.Cookies.Remove(cookie.Name);
                    e.Context.Response.Cookies.Add(cookie);
                }
            }
        }
Beispiel #56
0
        /////////////////////////////////////////////////////////////////////////////
        private static byte[] MakeTicketIntoBinaryBlob(FormsAuthenticationTicket ticket)
        {
            // None of the modes (Framework20 / Framework40 / beyond) support null values for these fields;
            // they always eventually just returned a null value.
            if (ticket.Name == null || ticket.UserData == null || ticket.CookiePath == null)
            {
                return(null);
            }

            // ** MSRC 11838 **
            // Framework20 / Framework40 ticket generation modes are insecure. We should use a
            // secure serialization mode by default.
            if (!AppSettings.UseLegacyFormsAuthenticationTicketCompatibility)
            {
                return(FormsAuthenticationTicketSerializer.Serialize(ticket));
            }

            // ** MSRC 11838 **
            // If we have reached this point of execution, the developer has explicitly elected
            // to continue using the insecure code path instead of the secure one. We removed
            // the Framework40 serialization mode, so everybody using the legacy code path is
            // forced to Framework20.

            byte [] bData  = new byte[4096];
            byte [] pBin   = new byte[4];
            long [] pDates = new long[2];
            byte [] pNull  = { 0, 0, 0 };

            // DevDiv Bugs 137864: 8 bytes may not be enough random bits as the length should be equal to the
            // key size. In CompatMode > Framework20SP1, use the IVType.Random feature instead of these 8 bytes,
            // but still include empty 8 bytes for compat with webengine.dll, where CookieAuthConstructTicket is.
            // Note that even in CompatMode = Framework20SP2 we fill 8 bytes with random data if the ticket
            // is not going to be encrypted.

            bool willEncrypt   = (_Protection == FormsProtectionEnum.All || _Protection == FormsProtectionEnum.Encryption);
            bool legacyPadding = !willEncrypt || (MachineKeySection.CompatMode == MachineKeyCompatibilityMode.Framework20SP1);

            if (legacyPadding)
            {
                // Fill the first 8 bytes of the blob with random bits
                byte[] bRandom = new byte[8];
                RNGCryptoServiceProvider randgen = new RNGCryptoServiceProvider();
                randgen.GetBytes(bRandom);
                Buffer.BlockCopy(bRandom, 0, bData, 0, 8);
            }
            else
            {
                // use blank 8 bytes for compatibility with CookieAuthConstructTicket (do nothing)
            }

            pBin[0] = (byte)ticket.Version;
            pBin[1] = (byte)(ticket.IsPersistent ? 1 : 0);

            pDates[0] = ticket.IssueDate.ToFileTime();
            pDates[1] = ticket.Expiration.ToFileTime();

            int iRet = UnsafeNativeMethods.CookieAuthConstructTicket(
                bData, bData.Length,
                ticket.Name, ticket.UserData, ticket.CookiePath,
                pBin, pDates);

            if (iRet < 0)
            {
                return(null);
            }

            byte[] ciphertext = new byte[iRet];
            Buffer.BlockCopy(bData, 0, ciphertext, 0, iRet);
            return(ciphertext);
        }
Beispiel #57
0
        ////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////
        // Private method for decrypting a cookie
        private static FormsAuthenticationTicket ExtractTicketFromCookie(HttpContext context, String name, out bool cookielessTicket)
        {
            FormsAuthenticationTicket ticket = null;
            string encValue      = null;
            bool   ticketExpired = false;
            bool   badTicket     = false;

            try {
                try {
                    ////////////////////////////////////////////////////////////
                    // Step 0: Check if we should use cookieless
                    cookielessTicket = CookielessHelperClass.UseCookieless(context, false, FormsAuthentication.CookieMode);

                    ////////////////////////////////////////////////////////////
                    // Step 1: Check URI/cookie for ticket
                    if (cookielessTicket)
                    {
                        encValue = context.CookielessHelper.GetCookieValue('F');
                    }
                    else
                    {
                        HttpCookie cookie = context.Request.Cookies[name];
                        if (cookie != null)
                        {
                            encValue = cookie.Value;
                        }
                    }

                    ////////////////////////////////////////////////////////////
                    // Step 2: Decrypt encrypted ticket
                    if (encValue != null && encValue.Length > 1)
                    {
                        try {
                            ticket = FormsAuthentication.Decrypt(encValue);
                        } catch {
                            if (cookielessTicket)
                            {
                                context.CookielessHelper.SetCookieValue('F', null);
                            }
                            else
                            {
                                context.Request.Cookies.Remove(name);
                            }
                            badTicket = true;
                            //throw;
                        }

                        if (ticket == null)
                        {
                            badTicket = true;
                        }

                        if (ticket != null && !ticket.Expired)
                        {
                            if (cookielessTicket || !FormsAuthentication.RequireSSL || context.Request.IsSecureConnection) // Make sure it is NOT a secure cookie over an in-secure connection
                            {
                                return(ticket);                                                                            // Found valid ticket
                            }
                        }

                        if (ticket != null && ticket.Expired)
                        {
                            ticketExpired = true;
                        }

                        // Step 2b: Remove expired/bad ticket
                        ticket = null;
                        if (cookielessTicket)
                        {
                            context.CookielessHelper.SetCookieValue('F', null);
                        }
                        else
                        {
                            context.Request.Cookies.Remove(name);
                        }
                    }


                    ////////////////////////////////////////////////////////////
                    // Step 3: Look in QueryString
                    if (FormsAuthentication.EnableCrossAppRedirects)
                    {
                        encValue = context.Request.QueryString[name];
                        if (encValue != null && encValue.Length > 1)
                        {
                            if (!cookielessTicket && FormsAuthentication.CookieMode == HttpCookieMode.AutoDetect)
                            {
                                cookielessTicket = CookielessHelperClass.UseCookieless(context, true, FormsAuthentication.CookieMode); // find out for sure
                            }
                            try {
                                ticket = FormsAuthentication.Decrypt(encValue);
                            } catch {
                                badTicket = true;
                                //throw;
                            }

                            if (ticket == null)
                            {
                                badTicket = true;
                            }
                        }

                        // Step 3b: Look elsewhere in the request (i.e. posted body)
                        if (ticket == null || ticket.Expired)
                        {
                            encValue = context.Request.Form[name];
                            if (encValue != null && encValue.Length > 1)
                            {
                                if (!cookielessTicket && FormsAuthentication.CookieMode == HttpCookieMode.AutoDetect)
                                {
                                    cookielessTicket = CookielessHelperClass.UseCookieless(context, true, FormsAuthentication.CookieMode); // find out for sure
                                }
                                try {
                                    ticket = FormsAuthentication.Decrypt(encValue);
                                } catch {
                                    badTicket = true;
                                    //throw;
                                }

                                if (ticket == null)
                                {
                                    badTicket = true;
                                }
                            }
                        }
                    }

                    if (ticket == null || ticket.Expired)
                    {
                        if (ticket != null && ticket.Expired)
                        {
                            ticketExpired = true;
                        }

                        return(null); // not found! Exit with null
                    }

                    if (FormsAuthentication.RequireSSL && !context.Request.IsSecureConnection) // Bad scenario: valid ticket over non-SSL
                    {
                        throw new HttpException(SR.GetString(SR.Connection_not_secure_creating_secure_cookie));
                    }

                    ////////////////////////////////////////////////////////////
                    // Step 4: Create the cookie/URI value
                    if (cookielessTicket)
                    {
                        if (ticket.CookiePath != "/")
                        {
                            FormsAuthenticationTicket tempTicket = FormsAuthenticationTicket.FromUtc(ticket.Version, ticket.Name, ticket.IssueDateUtc,
                                                                                                     ticket.ExpirationUtc, ticket.IsPersistent, ticket.UserData,
                                                                                                     "/");
                            ticket   = tempTicket;
                            encValue = FormsAuthentication.Encrypt(ticket);
                        }
                        context.CookielessHelper.SetCookieValue('F', encValue);
                        string strUrl = FormsAuthentication.RemoveQueryStringVariableFromUrl(context.Request.RawUrl, name);
                        context.Response.Redirect(strUrl);
                    }
                    else
                    {
                        HttpCookie cookie = new HttpCookie(name, encValue);
                        cookie.HttpOnly = true;
                        cookie.Path     = ticket.CookiePath;
                        if (ticket.IsPersistent)
                        {
                            cookie.Expires = ticket.Expiration;
                        }
                        cookie.Secure = FormsAuthentication.RequireSSL;
                        if (FormsAuthentication.CookieDomain != null)
                        {
                            cookie.Domain = FormsAuthentication.CookieDomain;
                        }
                        context.Response.Cookies.Remove(cookie.Name);
                        context.Response.Cookies.Add(cookie);
                    }

                    return(ticket);
                } finally {
                    if (badTicket)
                    {
                        WebBaseEvent.RaiseSystemEvent(null, WebEventCodes.AuditFormsAuthenticationFailure,
                                                      WebEventCodes.InvalidTicketFailure);
                    }
                    else if (ticketExpired)
                    {
                        WebBaseEvent.RaiseSystemEvent(null, WebEventCodes.AuditFormsAuthenticationFailure,
                                                      WebEventCodes.ExpiredTicketFailure);
                    }
                }
            } catch {
                throw;
            }
        }
Beispiel #58
0
    public string Login_pi(string username, string password)
    {
        t_Users dbUser = _userBL.GetUser(username);

        if (dbUser == null)
        {
            //ntf.VisibleOnPageLoad = true;
            //ntf.Text = "Sai ký danh hoặc mật khẩu.";
            //txtUsername.Focus();
            object result = new
            {
                resultId = 0,
                message  = "Wrong username. Please try again"
            };
            return(JsonConvert.SerializeObject(result));
        }
        //string hashedPassword = _stringUT.HashMD5(_stringUT.HashMD5(txtPassword.Text) + dbUser.Salt);
        string hashedPassword = _stringUT.HashMD5(_stringUT.HashMD5(password) + dbUser.Salt);

        if (string.Equals(hashedPassword, dbUser.Password))
        {
            HttpCookie cookie;

            System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(1, dbUser.Username, DateTime.Now,
                                                                                                                     DateTime.Now.AddMinutes(120),
                                                                                                                     true, dbUser.Role + "|" + dbUser.ConsumerId, System.Web.Security.FormsAuthentication.FormsCookiePath);
            string hashCookie = System.Web.Security.FormsAuthentication.Encrypt(ticket);
            cookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, hashCookie);
            Context.Response.Cookies.Add(cookie);
            t_Users user = new t_Users();
            user           = dbUser;
            user.LoginTime = user.LoginTime == null ? 0 : user.LoginTime + 1;
            _userBL.UpdateUser(user, dbUser);

            string message = "";
            if (dbUser.Role == "consumer" || dbUser.Role == "staff")
            {
                message = string.Format("Consumer/Logger/MapJS_rev1.aspx?uid={0}", user.Username);
            }
            else if (dbUser.Role == "vanviewer")
            {
                message = string.Format("VanViewer/BomControl/BomControl.aspx");
            }
            else
            {
                message = string.Format("Supervisor/Logger/MapJS_rev1.aspx?uid={0}", user.Username);
            }
            object result = new
            {
                resultId = 1,
                message  = message
            };
            return(JsonConvert.SerializeObject(result));
        }
        else
        {
            object result = new
            {
                resultId = 0,
                message  = "Wrong password. Please try again"
            };
            return(JsonConvert.SerializeObject(result));
        }
    }
Beispiel #59
0
        public void GetSettingPage()
        {
            DataSet _Ds;

            System.Web.HttpContext context = System.Web.HttpContext.Current;
            if (context.Request.Cookies[FormsAuthentication.FormsCookieName] == null)
            {
                //			        context.Response.Redirect("../Default.aspx");
                //					return;

                // Invalidate roles token
                context.Response.Cookies[FormsAuthentication.FormsCookieName].Value   = null;
                context.Response.Cookies[FormsAuthentication.FormsCookieName].Expires = new System.DateTime(1999, 10, 12);
                context.Response.Cookies[FormsAuthentication.FormsCookieName].Path    = "/";

                // Redirect user back to the Portal Home Page
                context.Response.Redirect(context.Request.ApplicationPath + "/Default.aspx");
                context.Response.End();
                Console.WriteLine("Entrato");
            }

            S_ControlsCollection _SCollection = new S_ControlsCollection();

            S_Controls.Collections.S_Object s_lnk = new S_Object();
            s_lnk.ParameterName = "p_path";
            s_lnk.DbType        = CustomDBType.VarChar;
            s_lnk.Direction     = ParameterDirection.Input;
            s_lnk.Size          = 255;
            s_lnk.Index         = 0;
            s_lnk.Value         = s_ModuleSrc;

            S_Controls.Collections.S_Object s_UserName = new S_Object();
            s_UserName.ParameterName = "p_UserName";
            s_UserName.DbType        = CustomDBType.VarChar;
            s_UserName.Direction     = ParameterDirection.Input;
            s_UserName.Size          = 50;
            s_UserName.Index         = 1;
            string s_User = string.Empty;

            if (context.User != null)
            {
                s_User = context.User.Identity.Name;
            }
            else
            {
                System.Web.Security.FormsAuthenticationTicket ticket = System.Web.Security.FormsAuthentication.Decrypt(context.Request.Cookies[FormsAuthentication.FormsCookieName].Value);

                s_User = ticket.Name;
            }
            s_UserName.Value = s_User;

            S_Controls.Collections.S_Object s_Cursor = new S_Object();
            s_Cursor.ParameterName = "IO_CURSOR";
            s_Cursor.DbType        = CustomDBType.Cursor;
            s_Cursor.Direction     = ParameterDirection.Output;
            s_Cursor.Index         = 2;

            _SCollection.Add(s_lnk);
            _SCollection.Add(s_UserName);
            _SCollection.Add(s_Cursor);

            ApplicationDataLayer.OracleDataLayer _OraDl = new OracleDataLayer(s_ConnStr);
            string s_StrSql = "PACK_SITO.SP_GETSETTINGS_PAGE";

            _Ds = _OraDl.GetRows(_SCollection, s_StrSql).Copy();

            if (_Ds.Tables[0].Rows.Count == 1)
            {
                this.s_ModuleTitle = _Ds.Tables[0].Rows[0]["DESCRIZIONE"].ToString();
                decimal i_Modifica = (decimal)_Ds.Tables[0].Rows[0]["ISMODIFICA"];
                this.i_ModuleId = int.Parse(_Ds.Tables[0].Rows[0]["FUNZIONE_ID"].ToString());

                if (i_Modifica < 0)
                {
                    this.b_IsEditable = true;
                }
                else
                {
                    this.b_IsEditable = false;
                }

                decimal i_Stampa = (decimal)_Ds.Tables[0].Rows[0]["ISSTAMPA"];
                if (i_Stampa < 0)
                {
                    this.b_IsPrintable = true;
                }
                else
                {
                    this.b_IsPrintable = false;
                }

                decimal i_Cancella = (decimal)_Ds.Tables[0].Rows[0]["ISCANCELLAZIONE"];
                if (i_Cancella < 0)
                {
                    this.b_IsDeletable = true;
                }
                else
                {
                    this.b_IsDeletable = false;
                }

                if (_Ds.Tables[0].Rows[0]["LINK"] != DBNull.Value)
                {
                    this.s_Link = _Ds.Tables[0].Rows[0]["LINK"].ToString();
                }
                if (_Ds.Tables[0].Rows[0]["LINK_HELP"] != DBNull.Value)
                {
                    this.s_HelpLink = System.Configuration.ConfigurationSettings.AppSettings["LinkHelp"] + _Ds.Tables[0].Rows[0]["LINK_HELP"].ToString();
                }
                //	this.s_HelpLink = _Ds.Tables[0].Rows[0]["LINK_HELP"].ToString();
            }
        }
Beispiel #60
0
        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        // Decrypt and get the auth ticket

        /// <devdoc>
        ///    <para>Given an encrypted authenitcation ticket as
        ///       obtained from an HTTP cookie, this method returns an instance of a
        ///       FormsAuthenticationTicket class.</para>
        /// </devdoc>
        public static FormsAuthenticationTicket Decrypt(string encryptedTicket)
        {
            if (String.IsNullOrEmpty(encryptedTicket) || encryptedTicket.Length > MAX_TICKET_LENGTH)
            {
                throw new ArgumentException(SR.GetString(SR.InvalidArgumentValue, "encryptedTicket"));
            }

            Initialize();
            byte[] bBlob = null;
            if ((encryptedTicket.Length % 2) == 0)   // Could be a hex string
            {
                try {
                    bBlob = CryptoUtil.HexToBinary(encryptedTicket);
                } catch { }
            }
            if (bBlob == null)
            {
                bBlob = HttpServerUtility.UrlTokenDecode(encryptedTicket);
            }
            if (bBlob == null || bBlob.Length < 1)
            {
                throw new ArgumentException(SR.GetString(SR.InvalidArgumentValue, "encryptedTicket"));
            }

            int ticketLength;

            if (AspNetCryptoServiceProvider.Instance.IsDefaultProvider)
            {
                // If new crypto routines are enabled, call them instead.
                ICryptoService cryptoService   = AspNetCryptoServiceProvider.Instance.GetCryptoService(Purpose.FormsAuthentication_Ticket);
                byte[]         unprotectedData = cryptoService.Unprotect(bBlob);
                ticketLength = unprotectedData.Length;
                bBlob        = unprotectedData;
            }
            else
            {
#pragma warning disable 618 // calling obsolete methods
                // Otherwise call into MachineKeySection routines.

                if (_Protection == FormsProtectionEnum.All || _Protection == FormsProtectionEnum.Encryption)
                {
                    // DevDiv Bugs 137864: Include a random IV if under the right compat mode
                    // for improved encryption semantics
                    bBlob = MachineKeySection.EncryptOrDecryptData(false, bBlob, null, 0, bBlob.Length, false, false, IVType.Random);
                    if (bBlob == null)
                    {
                        return(null);
                    }
                }

                ticketLength = bBlob.Length;

                if (_Protection == FormsProtectionEnum.All || _Protection == FormsProtectionEnum.Validation)
                {
                    if (!MachineKeySection.VerifyHashedData(bBlob))
                    {
                        return(null);
                    }
                    ticketLength -= MachineKeySection.HashSize;
                }
#pragma warning restore 618 // calling obsolete methods
            }

            //////////////////////////////////////////////////////////////////////
            // Step 4: Change binary ticket to managed struct

            // ** MSRC 11838 **
            // Framework20 / Framework40 ticket generation modes are insecure. We should use a
            // secure serialization mode by default.
            if (!AppSettings.UseLegacyFormsAuthenticationTicketCompatibility)
            {
                return(FormsAuthenticationTicketSerializer.Deserialize(bBlob, ticketLength));
            }

            // ** MSRC 11838 **
            // If we have reached this point of execution, the developer has explicitly elected
            // to continue using the insecure code path instead of the secure one. We removed
            // the Framework40 serialization mode, so everybody using the legacy code path is
            // forced to Framework20.

            int           iSize  = ((ticketLength > MAX_TICKET_LENGTH) ? MAX_TICKET_LENGTH : ticketLength);
            StringBuilder name   = new StringBuilder(iSize);
            StringBuilder data   = new StringBuilder(iSize);
            StringBuilder path   = new StringBuilder(iSize);
            byte []       pBin   = new byte[4];
            long []       pDates = new long[2];

            int iRet = UnsafeNativeMethods.CookieAuthParseTicket(bBlob, ticketLength,
                                                                 name, iSize,
                                                                 data, iSize,
                                                                 path, iSize,
                                                                 pBin, pDates);

            if (iRet != 0)
            {
                return(null);
            }

            DateTime dt1 = DateTime.FromFileTime(pDates[0]);
            DateTime dt2 = DateTime.FromFileTime(pDates[1]);

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket((int)pBin[0],
                                                                             name.ToString(),
                                                                             dt1,
                                                                             dt2,
                                                                             (bool)(pBin[1] != 0),
                                                                             data.ToString(),
                                                                             path.ToString());
            return(ticket);
        }