Example #1
0
        public static void ClearAnonymousIdentifier()
        {
            if (!s_Initialized)
            {
                Initialize();
            }

            HttpContext context = HttpContext.Current;

            if (context == null)
            {
                return;
            }

            // VSWhidbey 418835: When this feature is enabled, prevent infinite loop when cookieless
            // mode != Cookies and there was no cookie, also we cannot clear when current user is anonymous.
            if (!s_Enabled || !context.Request.IsAuthenticated)
            {
                throw new NotSupportedException(SR.GetString(SR.Anonymous_ClearAnonymousIdentifierNotSupported));
            }

            ////////////////////////////////////////////////////////////
            // Check if we need to clear the ticket stored in the URI
            bool clearUri = false;

            if (context.CookielessHelper.GetCookieValue('A') != null)
            {
                context.CookielessHelper.SetCookieValue('A', null); // Always clear the uri-cookie
                clearUri = true;
            }

            ////////////////////////////////////////////////////////////
            // Clear cookie if cookies are supported by the browser
            if (!CookielessHelperClass.UseCookieless(context, false, s_CookieMode) || context.Request.Browser.Cookies)
            { // clear cookie if required
                string cookieValue = String.Empty;
                if (context.Request.Browser["supportsEmptyStringInCookieValue"] == "false")
                {
                    cookieValue = "NoCookie";
                }
                HttpCookie cookie = new HttpCookie(s_CookieName, cookieValue);
                cookie.HttpOnly = true;
                cookie.Path     = s_CookiePath;
                cookie.Secure   = s_RequireSSL;
                if (s_Domain != null)
                {
                    cookie.Domain = s_Domain;
                }
                cookie.Expires = new System.DateTime(1999, 10, 12);
                context.Response.Cookies.RemoveCookie(s_CookieName);
                context.Response.Cookies.Add(cookie);
            }

            ////////////////////////////////////////////////////////////
            // Redirect back to this page if we removed a URI ticket
            if (clearUri)
            {
                context.Response.Redirect(context.Request.RawUrl, false);
            }
        }
Example #2
0
        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////

        /// <devdoc>
        ///    Given an authenticated user, calling SignOut
        ///    removes the authentication ticket by doing a SetForms with an empty value. This
        ///    removes either durable or session cookies.
        /// </devdoc>
        public static void SignOut()
        {
            Initialize();

            HttpContext context        = HttpContext.Current;
            bool        needToRedirect = context.CookielessHelper.DoesCookieValueExistInOriginal('F');

            context.CookielessHelper.SetCookieValue('F', null); // Always clear the uri-cookie

            if (!CookielessHelperClass.UseCookieless(context, false, CookieMode) || context.Request.Browser.Cookies)
            { // clear cookie if required
                string cookieValue = String.Empty;
                if (context.Request.Browser["supportsEmptyStringInCookieValue"] == "false")
                {
                    cookieValue = "NoCookie";
                }
                HttpCookie cookie = new HttpCookie(FormsCookieName, cookieValue);
                cookie.HttpOnly = true;
                cookie.Path     = _FormsCookiePath;
                cookie.Expires  = new System.DateTime(1999, 10, 12);
                cookie.Secure   = _RequireSSL;
                if (_CookieDomain != null)
                {
                    cookie.Domain = _CookieDomain;
                }
                cookie.SameSite = _cookieSameSite;
                context.Response.Cookies.RemoveCookie(FormsCookieName);
                context.Response.Cookies.Add(cookie);
            }
            if (needToRedirect)
            {
                context.Response.Redirect(GetLoginPage(null), false);
            }
        }
Example #3
0
        public static void SignOut()
        {
            Initialize();
            HttpContext current = HttpContext.Current;
            bool        flag    = current.CookielessHelper.DoesCookieValueExistInOriginal('F');

            current.CookielessHelper.SetCookieValue('F', null);
            if (!CookielessHelperClass.UseCookieless(current, false, CookieMode) || current.Request.Browser.Cookies)
            {
                string str = string.Empty;
                if (current.Request.Browser["supportsEmptyStringInCookieValue"] == "false")
                {
                    str = "NoCookie";
                }
                HttpCookie cookie = new HttpCookie(FormsCookieName, str)
                {
                    HttpOnly = true,
                    Path     = _FormsCookiePath,
                    Expires  = new DateTime(0x7cf, 10, 12),
                    Secure   = _RequireSSL
                };
                if (_CookieDomain != null)
                {
                    cookie.Domain = _CookieDomain;
                }
                current.Response.Cookies.RemoveCookie(FormsCookieName);
                current.Response.Cookies.Add(cookie);
            }
            if (flag)
            {
                current.Response.Redirect(GetLoginPage(null), false);
            }
        }
Example #4
0
        private void OnLeave(object source, EventArgs eventArgs)
        {
            if (this._fOnEnterCalled)
            {
                this._fOnEnterCalled = false;
            }
            else
            {
                return;
            }
            HttpApplication application = (HttpApplication)source;
            HttpContext     context     = application.Context;

            if (context.Response.Cookies.GetNoCreate(FormsAuthentication.FormsCookieName) != null)
            {
                context.Response.Cache.SetCacheability(HttpCacheability.NoCache, "Set-Cookie");
            }
            if (context.Response.StatusCode == 0x191)
            {
                string rawUrl = context.Request.RawUrl;
                if ((rawUrl.IndexOf("?ReturnUrl=", StringComparison.Ordinal) == -1) && (rawUrl.IndexOf("&ReturnUrl=", StringComparison.Ordinal) == -1))
                {
                    string str3;
                    string strUrl = null;
                    if (!string.IsNullOrEmpty(FormsAuthentication.LoginUrl))
                    {
                        strUrl = AuthenticationConfig.GetCompleteLoginUrl(context, FormsAuthentication.LoginUrl);
                    }
                    if ((strUrl == null) || (strUrl.Length <= 0))
                    {
                        throw new HttpException(System.Web.SR.GetString("Auth_Invalid_Login_Url"));
                    }
                    CookielessHelperClass cookielessHelper = context.CookielessHelper;
                    if (strUrl.IndexOf('?') >= 0)
                    {
                        str3 = FormsAuthentication.RemoveQueryStringVariableFromUrl(strUrl, "ReturnUrl") + "&ReturnUrl=" + HttpUtility.UrlEncode(rawUrl, context.Request.ContentEncoding);
                    }
                    else
                    {
                        str3 = strUrl + "?ReturnUrl=" + HttpUtility.UrlEncode(rawUrl, context.Request.ContentEncoding);
                    }
                    int index = rawUrl.IndexOf('?');
                    if ((index >= 0) && (index < (rawUrl.Length - 1)))
                    {
                        str3 = str3 + "&" + rawUrl.Substring(index + 1);
                    }
                    cookielessHelper.SetCookieValue('F', null);
                    cookielessHelper.RedirectWithDetectionIfRequired(str3, FormsAuthentication.CookieMode);
                    context.Response.Redirect(str3, false);
                }
            }
        }
        public static void ClearAnonymousIdentifier()
        {
            if (!s_Initialized)
            {
                Initialize();
            }
            HttpContext current = HttpContext.Current;

            if (current != null)
            {
                if (!s_Enabled || !current.Request.IsAuthenticated)
                {
                    throw new NotSupportedException(System.Web.SR.GetString("Anonymous_ClearAnonymousIdentifierNotSupported"));
                }
                bool flag = false;
                if (current.CookielessHelper.GetCookieValue('A') != null)
                {
                    current.CookielessHelper.SetCookieValue('A', null);
                    flag = true;
                }
                if (!CookielessHelperClass.UseCookieless(current, false, s_CookieMode) || current.Request.Browser.Cookies)
                {
                    string str = string.Empty;
                    if (current.Request.Browser["supportsEmptyStringInCookieValue"] == "false")
                    {
                        str = "NoCookie";
                    }
                    HttpCookie cookie = new HttpCookie(s_CookieName, str)
                    {
                        HttpOnly = true,
                        Path     = s_CookiePath,
                        Secure   = s_RequireSSL
                    };
                    if (s_Domain != null)
                    {
                        cookie.Domain = s_Domain;
                    }
                    cookie.Expires = new DateTime(0x7cf, 10, 12);
                    current.Response.Cookies.RemoveCookie(s_CookieName);
                    current.Response.Cookies.Add(cookie);
                }
                if (flag)
                {
                    current.Response.Redirect(current.Request.RawUrl, false);
                }
            }
        }
Example #6
0
        private void OnEnter(object source, EventArgs eventArgs)
        {
            this._fOnEnterCalled = true;
            HttpApplication application = (HttpApplication)source;
            HttpContext     context     = application.Context;

            this.OnAuthenticate(new FormsAuthenticationEventArgs(context));
            CookielessHelperClass cookielessHelper = context.CookielessHelper;

            if (AuthenticationConfig.AccessingLoginPage(context, FormsAuthentication.LoginUrl))
            {
                context.SetSkipAuthorizationNoDemand(true, false);
                cookielessHelper.RedirectWithDetectionIfRequired(null, FormsAuthentication.CookieMode);
            }
            if (!context.SkipAuthorization)
            {
                context.SetSkipAuthorizationNoDemand(AssemblyResourceLoader.IsValidWebResourceRequest(context), false);
            }
        }
Example #7
0
        /// <devdoc>
        ///    This method creates an authentication ticket
        ///    for the given userName and attaches it to the cookies collection of the outgoing
        ///    response. It does not perform a redirect.
        /// </devdoc>
        public static void SetAuthCookie(String userName, bool createPersistentCookie, String strCookiePath)
        {
            Initialize();
            HttpContext context = HttpContext.Current;

            if (!context.Request.IsSecureConnection && RequireSSL)
            {
                throw new HttpException(SR.GetString(SR.Connection_not_secure_creating_secure_cookie));
            }
            bool       cookieless = CookielessHelperClass.UseCookieless(context, false, CookieMode);
            HttpCookie cookie     = GetAuthCookie(userName, createPersistentCookie, cookieless ? "/" : strCookiePath, !cookieless);

            if (!cookieless)
            {
                HttpContext.Current.Response.Cookies.Add(cookie);
                context.CookielessHelper.SetCookieValue('F', null);
            }
            else
            {
                context.CookielessHelper.SetCookieValue('F', cookie.Value);
            }
        }
Example #8
0
        ////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        private void OnEnter(Object source, EventArgs eventArgs)
        {
            _fOnEnterCalled = true;

            HttpApplication app;
            HttpContext     context;

            app     = (HttpApplication)source;
            context = app.Context;

#if DBG
            Trace("*******************Request path: " + context.Request.RawUrl);
#endif

            ////////////////////////////////////////////////////////
            // Step 2: Call OnAuthenticate virtual method to create
            //    an IPrincipal for this request
            OnAuthenticate(new FormsAuthenticationEventArgs(context));

            ////////////////////////////////////////////////////////
            // Skip AuthZ if accessing the login page

            // We do this here to force the cookieless helper to fish out and
            // remove the token from the URL if it's present there.
            CookielessHelperClass cookielessHelper = context.CookielessHelper;

            if (AuthenticationConfig.AccessingLoginPage(context, FormsAuthentication.LoginUrl))
            {
                context.SetSkipAuthorizationNoDemand(true, false /*managedOnly*/);
                cookielessHelper.RedirectWithDetectionIfRequired(null, FormsAuthentication.CookieMode);
            }
            if (!context.SkipAuthorization)
            {
                context.SetSkipAuthorizationNoDemand(AssemblyResourceLoader.IsValidWebResourceRequest(context), false /*managedOnly*/);
            }
        }
Example #9
0
        ////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        private void OnEnter(Object source, EventArgs eventArgs)
        {
            if (!s_Initialized)
            {
                Initialize();
            }

            if (!s_Enabled)
            {
                return;
            }

            HttpApplication app;
            HttpContext     context;
            HttpCookie      cookie       = null;
            bool            createCookie = false;
            AnonymousIdData decodedValue = null;
            bool            cookieLess;
            string          encValue        = null;
            bool            isAuthenticated = false;

            app     = (HttpApplication)source;
            context = app.Context;

            isAuthenticated = context.Request.IsAuthenticated;

            if (isAuthenticated)
            {
                cookieLess = CookielessHelperClass.UseCookieless(context, false /* no redirect */, s_CookieMode);
            }
            else
            {
                cookieLess = CookielessHelperClass.UseCookieless(context, true /* do redirect */, s_CookieMode);
                //if (!cookieLess && s_RequireSSL && !context.Request.IsSecureConnection)
                //    throw new HttpException(SR.GetString(SR.Connection_not_secure_creating_secure_cookie));
            }

            ////////////////////////////////////////////////////////////////////////
            // Handle secure-cookies over non SSL
            if (s_RequireSSL && !context.Request.IsSecureConnection)
            {
                if (!cookieLess)
                {
                    cookie = context.Request.Cookies[s_CookieName];
                    if (cookie != null)
                    {
                        cookie          = new HttpCookie(s_CookieName, String.Empty);
                        cookie.HttpOnly = true;
                        cookie.Path     = s_CookiePath;
                        cookie.Secure   = s_RequireSSL;
                        if (s_Domain != null)
                        {
                            cookie.Domain = s_Domain;
                        }
                        cookie.Expires = new System.DateTime(1999, 10, 12);

                        if (context.Request.Browser["supportsEmptyStringInCookieValue"] == "false")
                        {
                            cookie.Value = "NoCookie";
                        }
                        context.Response.Cookies.Add(cookie);
                    }

                    return;
                }
            }


            ////////////////////////////////////////////////////////////
            // Step 2: See if cookie, or cookie-header has the value
            if (!cookieLess)
            {
                cookie = context.Request.Cookies[s_CookieName];
                if (cookie != null)
                {
                    encValue    = cookie.Value;
                    cookie.Path = s_CookiePath;
                    if (s_Domain != null)
                    {
                        cookie.Domain = s_Domain;
                    }
                }
            }
            else
            {
                encValue = context.CookielessHelper.GetCookieValue('A');
            }

            decodedValue = GetDecodedValue(encValue);

            if (decodedValue != null && decodedValue.AnonymousId != null)
            {
                // Copy existing value in Request
                context.Request.AnonymousID = decodedValue.AnonymousId;
            }
            if (isAuthenticated) // For the authenticated case, we are done
            {
                return;
            }

            if (context.Request.AnonymousID == null)
            {
                ////////////////////////////////////////////////////////////
                // Step 3: Create new Identity

                // Raise event
                if (_CreateNewIdEventHandler != null)
                {
                    AnonymousIdentificationEventArgs e = new AnonymousIdentificationEventArgs(context);
                    _CreateNewIdEventHandler(this, e);
                    context.Request.AnonymousID = e.AnonymousID;
                }

                // Create from GUID
                if (string.IsNullOrEmpty(context.Request.AnonymousID))
                {
                    context.Request.AnonymousID = Guid.NewGuid().ToString("D", CultureInfo.InvariantCulture);
                }
                else
                {
                    if (context.Request.AnonymousID.Length > MAX_ID_LENGTH)
                    {
                        throw new HttpException(SR.GetString(SR.Anonymous_id_too_long));
                    }
                }
                if (s_RequireSSL && !context.Request.IsSecureConnection && !cookieLess)
                {
                    return; // Don't create secure-cookie in un-secured connection
                }
                createCookie = true;
            }

            ////////////////////////////////////////////////////////////
            // Step 4: Check if cookie has to be created
            DateTime dtNow = DateTime.UtcNow;

            if (!createCookie)
            {
                if (s_SlidingExpiration)
                {
                    if (decodedValue == null || decodedValue.ExpireDate < dtNow)
                    {
                        createCookie = true;
                    }
                    else
                    {
                        double secondsLeft = (decodedValue.ExpireDate - dtNow).TotalSeconds;
                        if (secondsLeft < (double)((s_CookieTimeout * 60) / 2))
                        {
                            createCookie = true;
                        }
                    }
                }
            }

            ////////////////////////////////////////////////////////////
            // Step 4: Create new cookie or cookieless header
            if (createCookie)
            {
                DateTime dtExpireTime = dtNow.AddMinutes(s_CookieTimeout);
                encValue = GetEncodedValue(new AnonymousIdData(context.Request.AnonymousID, dtExpireTime));
                if (encValue.Length > MAX_ENCODED_COOKIE_STRING)
                {
                    throw new HttpException(SR.GetString(SR.Anonymous_id_too_long_2));
                }

                if (!cookieLess)
                {
                    cookie          = new HttpCookie(s_CookieName, encValue);
                    cookie.HttpOnly = true;
                    cookie.Expires  = dtExpireTime;
                    cookie.Path     = s_CookiePath;
                    cookie.Secure   = s_RequireSSL;
                    if (s_Domain != null)
                    {
                        cookie.Domain = s_Domain;
                    }
                    context.Response.Cookies.Add(cookie);
                }
                else
                {
                    context.CookielessHelper.SetCookieValue('A', encValue);
                    context.Response.Redirect(context.Request.RawUrl);
                }
            }
        }
 private void OnEnter(object source, EventArgs eventArgs)
 {
     if (!s_Initialized)
     {
         Initialize();
     }
     if (s_Enabled)
     {
         bool            flag2;
         HttpCookie      cookie          = null;
         bool            flag            = false;
         AnonymousIdData decodedValue    = null;
         string          cookieValue     = null;
         bool            isAuthenticated = false;
         HttpApplication application     = (HttpApplication)source;
         HttpContext     context         = application.Context;
         isAuthenticated = context.Request.IsAuthenticated;
         if (isAuthenticated)
         {
             flag2 = CookielessHelperClass.UseCookieless(context, false, s_CookieMode);
         }
         else
         {
             flag2 = CookielessHelperClass.UseCookieless(context, true, s_CookieMode);
         }
         if ((s_RequireSSL && !context.Request.IsSecureConnection) && !flag2)
         {
             if (context.Request.Cookies[s_CookieName] != null)
             {
                 cookie = new HttpCookie(s_CookieName, string.Empty)
                 {
                     HttpOnly = true,
                     Path     = s_CookiePath,
                     Secure   = s_RequireSSL
                 };
                 if (s_Domain != null)
                 {
                     cookie.Domain = s_Domain;
                 }
                 cookie.Expires = new DateTime(0x7cf, 10, 12);
                 if (context.Request.Browser["supportsEmptyStringInCookieValue"] == "false")
                 {
                     cookie.Value = "NoCookie";
                 }
                 context.Response.Cookies.Add(cookie);
             }
         }
         else
         {
             if (!flag2)
             {
                 cookie = context.Request.Cookies[s_CookieName];
                 if (cookie != null)
                 {
                     cookieValue = cookie.Value;
                     cookie.Path = s_CookiePath;
                     if (s_Domain != null)
                     {
                         cookie.Domain = s_Domain;
                     }
                 }
             }
             else
             {
                 cookieValue = context.CookielessHelper.GetCookieValue('A');
             }
             decodedValue = GetDecodedValue(cookieValue);
             if ((decodedValue != null) && (decodedValue.AnonymousId != null))
             {
                 context.Request._AnonymousId = decodedValue.AnonymousId;
             }
             if (!isAuthenticated)
             {
                 if (context.Request._AnonymousId == null)
                 {
                     if (this._CreateNewIdEventHandler != null)
                     {
                         AnonymousIdentificationEventArgs e = new AnonymousIdentificationEventArgs(context);
                         this._CreateNewIdEventHandler(this, e);
                         context.Request._AnonymousId = e.AnonymousID;
                     }
                     if (string.IsNullOrEmpty(context.Request._AnonymousId))
                     {
                         context.Request._AnonymousId = Guid.NewGuid().ToString("D", CultureInfo.InvariantCulture);
                     }
                     else if (context.Request._AnonymousId.Length > 0x80)
                     {
                         throw new HttpException(System.Web.SR.GetString("Anonymous_id_too_long"));
                     }
                     if ((s_RequireSSL && !context.Request.IsSecureConnection) && !flag2)
                     {
                         return;
                     }
                     flag = true;
                 }
                 DateTime utcNow = DateTime.UtcNow;
                 if (!flag && s_SlidingExpiration)
                 {
                     if ((decodedValue == null) || (decodedValue.ExpireDate < utcNow))
                     {
                         flag = true;
                     }
                     else
                     {
                         TimeSpan span = (TimeSpan)(decodedValue.ExpireDate - utcNow);
                         if (span.TotalSeconds < ((s_CookieTimeout * 60) / 2))
                         {
                             flag = true;
                         }
                     }
                 }
                 if (flag)
                 {
                     DateTime dt = utcNow.AddMinutes((double)s_CookieTimeout);
                     cookieValue = GetEncodedValue(new AnonymousIdData(context.Request.AnonymousID, dt));
                     if (cookieValue.Length > 0x200)
                     {
                         throw new HttpException(System.Web.SR.GetString("Anonymous_id_too_long_2"));
                     }
                     if (!flag2)
                     {
                         cookie = new HttpCookie(s_CookieName, cookieValue)
                         {
                             HttpOnly = true,
                             Expires  = dt,
                             Path     = s_CookiePath,
                             Secure   = s_RequireSSL
                         };
                         if (s_Domain != null)
                         {
                             cookie.Domain = s_Domain;
                         }
                         context.Response.Cookies.Add(cookie);
                     }
                     else
                     {
                         context.CookielessHelper.SetCookieValue('A', cookieValue);
                         context.Response.Redirect(context.Request.RawUrl);
                     }
                 }
             }
         }
     }
 }
Example #11
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;
            }
        }
Example #12
0
        private static FormsAuthenticationTicket ExtractTicketFromCookie(HttpContext context, string name, out bool cookielessTicket)
        {
            FormsAuthenticationTicket ticket = null;
            string encryptedTicket           = null;
            FormsAuthenticationTicket ticket2;
            bool flag  = false;
            bool flag2 = false;

            try
            {
                try
                {
                    cookielessTicket = CookielessHelperClass.UseCookieless(context, false, FormsAuthentication.CookieMode);
                    if (cookielessTicket)
                    {
                        encryptedTicket = context.CookielessHelper.GetCookieValue('F');
                    }
                    else
                    {
                        HttpCookie cookie = context.Request.Cookies[name];
                        if (cookie != null)
                        {
                            encryptedTicket = cookie.Value;
                        }
                    }
                    if ((encryptedTicket != null) && (encryptedTicket.Length > 1))
                    {
                        try
                        {
                            ticket = FormsAuthentication.Decrypt(encryptedTicket);
                        }
                        catch
                        {
                            if (cookielessTicket)
                            {
                                context.CookielessHelper.SetCookieValue('F', null);
                            }
                            else
                            {
                                context.Request.Cookies.Remove(name);
                            }
                            flag2 = true;
                        }
                        if (ticket == null)
                        {
                            flag2 = true;
                        }
                        if (((ticket != null) && !ticket.Expired) && ((cookielessTicket || !FormsAuthentication.RequireSSL) || context.Request.IsSecureConnection))
                        {
                            return(ticket);
                        }
                        if ((ticket != null) && ticket.Expired)
                        {
                            flag = true;
                        }
                        ticket = null;
                        if (cookielessTicket)
                        {
                            context.CookielessHelper.SetCookieValue('F', null);
                        }
                        else
                        {
                            context.Request.Cookies.Remove(name);
                        }
                    }
                    if (FormsAuthentication.EnableCrossAppRedirects)
                    {
                        encryptedTicket = context.Request.QueryString[name];
                        if ((encryptedTicket != null) && (encryptedTicket.Length > 1))
                        {
                            if (!cookielessTicket && (FormsAuthentication.CookieMode == HttpCookieMode.AutoDetect))
                            {
                                cookielessTicket = CookielessHelperClass.UseCookieless(context, true, FormsAuthentication.CookieMode);
                            }
                            try
                            {
                                ticket = FormsAuthentication.Decrypt(encryptedTicket);
                            }
                            catch
                            {
                                flag2 = true;
                            }
                            if (ticket == null)
                            {
                                flag2 = true;
                            }
                        }
                        if ((ticket == null) || ticket.Expired)
                        {
                            encryptedTicket = context.Request.Form[name];
                            if ((encryptedTicket != null) && (encryptedTicket.Length > 1))
                            {
                                if (!cookielessTicket && (FormsAuthentication.CookieMode == HttpCookieMode.AutoDetect))
                                {
                                    cookielessTicket = CookielessHelperClass.UseCookieless(context, true, FormsAuthentication.CookieMode);
                                }
                                try
                                {
                                    ticket = FormsAuthentication.Decrypt(encryptedTicket);
                                }
                                catch
                                {
                                    flag2 = true;
                                }
                                if (ticket == null)
                                {
                                    flag2 = true;
                                }
                            }
                        }
                    }
                    if ((ticket == null) || ticket.Expired)
                    {
                        if ((ticket != null) && ticket.Expired)
                        {
                            flag = true;
                        }
                        return(null);
                    }
                    if (FormsAuthentication.RequireSSL && !context.Request.IsSecureConnection)
                    {
                        throw new HttpException(System.Web.SR.GetString("Connection_not_secure_creating_secure_cookie"));
                    }
                    if (cookielessTicket)
                    {
                        if (ticket.CookiePath != "/")
                        {
                            ticket          = FormsAuthenticationTicket.FromUtc(ticket.Version, ticket.Name, ticket.IssueDateUtc, ticket.ExpirationUtc, ticket.IsPersistent, ticket.UserData, "/");
                            encryptedTicket = FormsAuthentication.Encrypt(ticket);
                        }
                        context.CookielessHelper.SetCookieValue('F', encryptedTicket);
                        string url = FormsAuthentication.RemoveQueryStringVariableFromUrl(context.Request.RawUrl, name);
                        context.Response.Redirect(url);
                    }
                    else
                    {
                        HttpCookie cookie2 = new HttpCookie(name, encryptedTicket)
                        {
                            HttpOnly = true,
                            Path     = ticket.CookiePath
                        };
                        if (ticket.IsPersistent)
                        {
                            cookie2.Expires = ticket.Expiration;
                        }
                        cookie2.Secure = FormsAuthentication.RequireSSL;
                        if (FormsAuthentication.CookieDomain != null)
                        {
                            cookie2.Domain = FormsAuthentication.CookieDomain;
                        }
                        context.Response.Cookies.Remove(cookie2.Name);
                        context.Response.Cookies.Add(cookie2);
                    }
                    ticket2 = ticket;
                }
                finally
                {
                    if (flag2)
                    {
                        WebBaseEvent.RaiseSystemEvent(null, 0xfa5, 0xc419);
                    }
                    else if (flag)
                    {
                        WebBaseEvent.RaiseSystemEvent(null, 0xfa5, 0xc41a);
                    }
                }
            }
            catch
            {
                throw;
            }
            return(ticket2);
        }