cookie по умолчанию небезопасный, но безопасный в SSL - PullRequest
2 голосов
/ 11 августа 2010

У меня есть GUI, когда я вхожу в систему, я создаю cookie и зашифрую его. Я использую SSL.

Я проверяю на странице Login.aspx, является ли файл cookie безопасным, чем он и является. но затем перед переходом на страницу по умолчанию она переходит на страницу Global.ascx.

Здесь, в Application_AuthenticateRequest, он получает cookie и расшифровывает его для страницы по умолчанию.

Теперь я знаю, что он получает тот же файл cookie, что и все остальные атрибуты, совпадающие с тем, который был создан на странице Login.aspx, за исключением того, что безопасное значение равно «False».

это относится ко всем остальным страницам после дефолта. значение cookie.secure равно false.

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

Также страницы открываются как https, а не http.

вот мой web.config

        <authentication mode="Forms">
        <forms loginUrl="Login.aspx" defaultUrl="~/Default.aspx" name="copiunGUI" slidingExpiration="true" timeout="120" path="/" requireSSL="true" protection="All">
        </forms>
    </authentication>
<httpCookies requireSSL="true"/>
    <authorization>
        <deny users="?"/>
    </authorization>

мой код global.aspx

   protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        // Extract the forms authentication cookie

        string redirectSecureUrl = Request.Url.ToString();
        new GUIUtility().LogMessageToFile(redirectSecureUrl);

        string cookieName = FormsAuthentication.FormsCookieName.ToString();
        HttpCookie authCookie = Context.Request.Cookies[cookieName];

        try
        {
            new GUIUtility().LogMessageToFile(cookieName + authCookie.Secure + authCookie.Name + authCookie.Expires + authCookie.Path);
        }
        catch (Exception)
        {
            //
        }

        if (null == authCookie)
        {
            try
            {
                new GUIUtility().LogMessageToFile("authCookie = null");
            }
            catch (Exception)
            {
                //
            }

            // There is no authentication cookie.
            return;
        }

        FormsAuthenticationTicket authTicket = null;
        try
        {
            authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        }
        catch (Exception)
        {
            // Log exception details (omitted for simplicity)
            return;
        }

        if (null == authTicket)
        {
            // Cookie failed to decrypt.
            return;
        }

        // When the ticket was created, the UserData property was assigned a
        // pipe delimited string of role names.
        string[] roles = authTicket.UserData.Split(new char[] { '|' });

        // Create an Identity object
        FormsIdentity id = new FormsIdentity(authTicket);

        // This principal will flow throughout the request.
        GenericPrincipal principal = new GenericPrincipal(id, roles);
        // Attach the new principal object to the current HttpContext object
        Context.User = principal;
    }

код на моей странице login.aspx

 // Create the authentication ticket
                    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,                          // version
                                                   UserName.Text,           // user name
                                                   DateTime.Now,               // creation
                                                   DateTime.Now.AddMinutes(60),// Expiration
                                                   false,                      // Persistent 
                                                   role);         // User data

                    // Now encrypt the ticket.
                    string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

                    // Create a cookie and add the encrypted ticket to the
                    // cookie as data.
                    HttpCookie authCookie =
                                 new HttpCookie(FormsAuthentication.FormsCookieName,
                                                encryptedTicket);

                    if (authCookie.Secure)
                    {
                        new GUIUtility().LogMessageToFile("The cookie is secure with SSL." + authCookie.Name + authCookie.Expires + authCookie.Path);
                    }

                    //authCookie.Secure = FormsAuthentication.RequireSSL;

                    // Add the cookie to the outgoing cookies collection.
                    HttpContext.Current.Response.Cookies.Add(authCookie);

                    // Redirect the user to the originally requested page
                    string goToPath = FormsAuthentication.GetRedirectUrl(UserName.Text, true);
                    new GUIUtility().LogMessageToFile(goToPath);
                    //here the value of gotoPath is /Default.aspx
                    Response.Redirect(FormsAuthentication.GetRedirectUrl(UserName.Text,false));

1 Ответ

1 голос
/ 11 августа 2010

Я всегда задавался вопросом об этом.Я попытался установить RequireSSL = "true", но я продолжал получать новые сеансы, и мои входы не длились больше, чем запрос.Когда я смотрел на подкрепления, пытаясь понять, что происходит, я понял, что файлы cookie являются лишь частью HTTP-запроса и ответа и, похоже, не выходят отдельно.Поэтому, если я находился на незащищенной странице, браузер не передавал cookie на мой веб-сайт.

Если вам нужна его безопасность, я думаю, что вам нужно перевернуть весь сеанс, чтобы использовать https после cookieустановлен, иначе он не будет передан и потенциально будет перезаписан при следующем запросе, когда IIS / ASP.net не получит файл cookie сеанса, который он искал (я уверен, что именно поэтому я продолжал получать новые сеансы).

...