как работать с функцией входа и выхода с помощью asp. net 4.0 с c# - PullRequest
0 голосов
/ 23 февраля 2020

Я только что разработал одно веб-приложение. Я использую кэш-память для хранения предыдущего входа пользователя. вот мой код для страницы входа в систему.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            HttpContext.Current.Cache.Remove("previous_users");
            //password.Attributes.Add("value", "admin123");
            checkForCookiePersistent();
            bindLogo();
        }
    } 

 protected void Page_Init(object sender, EventArgs e)
    {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetExpires(DateTime.Now.AddHours(-1));
        Response.Cache.SetNoStore();
    }

private void checkForCookiePersistent()
    {
        try
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

            if (cookie != null && cookie.Value != string.Empty)
            {
                DataSet objUser = LoginLibrary.Business.SMSUser.VLUser.GetUserByUserName(SiteUser.Current().UserName);

                //string urlPath = HOMEPAGEPATH;
                string urlPath = GetPath(Convert.ToInt16(objUser.Tables[0].Rows[0]["intUserType"]));// +PAGEPATH;
                //if (objUser != null && objUser.PasswordExpiryDate <= DateTime.Now)
                //    urlPath = CHANGEPASSWORDPATH + true;
                // if (!HttpContext.Current.Request.Path.EndsWith("login.aspx", StringComparison.InvariantCultureIgnoreCase))
                {
                    (new MeridianURL(urlPath)).RedirectPage();
                }
            }
        }
        catch (Exception ex)
        {
        }
    }

protected void btnSignId_Click(object sender, EventArgs e)
    {
        DoLogin();
        //Server.Transfer("UserDashboard.aspx");
    }

и вот моя страница функции выхода из системы ..

public partial class GUI_Logout : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        LogOut();
    }
    public static void LogOut()
    {
        //clear session 
        string DomainName = HttpContext.Current.Request.Url.Host;

        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
        HttpContext.Current.Response.Cache.SetNoStore();

        //if (SiteUser.Current() != null && SiteUser.Current().isChiled)
        //{

        //    var obj = LoginLibrary.Business.SiteUser.Userloginbyid(SiteUser.Current().Parentid ,SiteUser.Current().Parentid );
        //    //ds = sql.ExecuteDataset("BulkSMS_ViewUserbyId", ID);
        //    //ds.Tables[0].TableName = "Data";
        //    FormsAuthenticationTicket ticket = null;

        //    ticket = new FormsAuthenticationTicket(
        //            1,              // Ticket version
        //            obj.UserName,   // Username associated with ticket
        //            DateTime.Now,   // Date/time issued
        //            DateTime.Now.AddYears(100), // Date/time to expire
        //            false, // "true" for a persistent user cookie
        //            "FullRight", // 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
        //    HttpContext.Current.Response.Cookies.Add(cookie);

        //    HttpContext.Current.Response.Redirect("Dashboard.aspx", true);
        //}
        //else
        {
            short UserId = 0;
            HttpContext.Current.Session.Clear();

            if (SiteUser.Current() == null)
            {
                if (DomainName.Contains("localhost"))
                {
                    HttpContext.Current.Response.Redirect("login.aspx");
                }
                else
                {
                    HttpContext.Current.Response.Redirect("Rlogin.aspx");
                }
                return;
            }
            else
                UserId = SiteUser.Current().UserID;



            HttpContext.Current.Cache.Remove("user_" + SiteUser.Current().UserName);
            HttpContext.Current.Cache.Remove("resolution");
            HttpContext.Current.Cache.Remove("SelectedParameters");

            //signout authenticate cookie
            FormsAuthentication.SignOut();

            // Code disables caching by browser.
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
            HttpContext.Current.Response.Cache.SetNoStore();


            ReLogin(UserId);
        }
    }
    protected void Timer1_Tick(object sender, EventArgs e)
    {

        if (HttpContext.Current.Request.Url.Host.Contains("localhost"))
        {
            HttpContext.Current.Response.Redirect("login.aspx", true);
        }
        else
        {
            Response.Redirect("Login.aspx");
        }
    }

    private static void ReLogin(short UserId)
    {
        List<short> previousUsers = new List<short>();
        if (System.Web.HttpContext.Current.Cache["previous_users"] != null)
            previousUsers = (List<short>)(HttpContext.Current.Cache["previous_users"]);

        if (previousUsers.Count > 0)
            previousUsers.RemoveAll(user => user == UserId);

        HttpContext.Current.Cache["previous_users"] = previousUsers;

        int LoginUserId = 0;
        if (previousUsers.Count > 0)
            LoginUserId = previousUsers[previousUsers.Count - 1];

        if (LoginUserId > 0)
        {
            try
            {
                var obj = LoginLibrary.Business.SiteUser.Userloginbyid(LoginUserId, LoginUserId);
                FormsAuthenticationTicket ticket = null;

                ticket = new FormsAuthenticationTicket(
                        1, // Ticket version
                        obj.UserName, // Username associated with ticket
                        DateTime.Now, // Date/time issued
                        DateTime.Now.AddYears(100), // Date/time to expire
                        false, // "true" for a persistent user cookie
                        "FullRight", // 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  
                HttpContext.Current.Response.Cookies.Add(cookie);

                string urlPath = GetPath(obj.UserType);// +PAGEPATH;
                HttpContext.Current.Response.Redirect(urlPath);

                //HttpContext.Current.Response.Redirect("Dashboard.aspx");
            }
            catch (Exception ex)
            {
                AppGlobal.Logger.WriteToErrorLogFile("Error: " + ex.ToString());
            }
        }
    }
    public static string GetPath(short userType)
    {
        string retPath = string.Empty;
        switch (userType)
        {
            case 0: retPath = "/GUI/adminDashbourd.aspx"; break;
            case 1: retPath = "/GUI/adminDashbourd.aspx"; break;
            case 2: retPath = "/GUI/RDashboard.aspx"; break;
            case 3: retPath = "/GUI/Dashboard.aspx"; break;
            default:
                retPath = "Dashboard.aspx";
                break;
        }
        return retPath;
    }
}

как бы это ни работало на одной машине. Администратор может перенаправить другую учетную запись пользователя и работает нормально, но никогда не выходить из своей учетной записи. теперь другой компьютер запрашивает этот же логин как обычный пользователь и работает в нем, когда он выходит из своей учетной записи с помощью нажатия кнопки logot, после чего открывается предыдущий пользователь, который является панелью администратора. что является проблемой безопасности.

как лучше всего обрабатывать логины пользователей с кешем памяти ... пожалуйста, ребята, помогите мне решить эту проблему.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...