Ejemplo n.º 1
0
    /// <summary>
    /// Save the temp data to the request.
    /// </summary>
    /// <param name="context">The <see cref="HttpContext"/>.</param>
    /// <param name="values">The values.</param>
    public void SaveTempData(HttpContext context, IDictionary <string, object> values)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        var cookieOptions = _options.Cookie.Build(context);

        SetCookiePath(context, cookieOptions);

        var hasValues = (values != null && values.Count > 0);

        if (hasValues)
        {
            var bytes = _tempDataSerializer.Serialize(values);
            bytes = _dataProtector.Protect(bytes);
            var encodedValue = WebEncoders.Base64UrlEncode(bytes);
            _chunkingCookieManager.AppendResponseCookie(context, _options.Cookie.Name, encodedValue, cookieOptions);
        }
        else
        {
            _chunkingCookieManager.DeleteCookie(context, _options.Cookie.Name, cookieOptions);
        }
    }
Ejemplo n.º 2
0
        public void SaveTempData_ProtectsAnd_Base64UrlEncodesDataAnd_SetsCookie()
        {
            // Arrange
            var values = new Dictionary <string, object>();

            values.Add("int", 10);
            var tempDataProviderStore = new TempDataSerializer();
            var expectedDataToProtect = tempDataProviderStore.Serialize(values);
            var expectedDataInCookie  = WebEncoders.Base64UrlEncode(expectedDataToProtect);
            var dataProtector         = new PassThroughDataProtector();
            var tempDataProvider      = GetProvider(dataProtector);
            var responseCookies       = new MockResponseCookieCollection();
            var httpContext           = new Mock <HttpContext>();

            httpContext
            .SetupGet(hc => hc.Request.PathBase)
            .Returns("/");
            httpContext
            .Setup(hc => hc.Response.Cookies)
            .Returns(responseCookies);

            // Act
            tempDataProvider.SaveTempData(httpContext.Object, values);

            // Assert
            Assert.Equal(1, responseCookies.Count);
            var cookieInfo = responseCookies[CookieTempDataProvider.CookieName];

            Assert.NotNull(cookieInfo);
            Assert.Equal(expectedDataInCookie, cookieInfo.Value);
            Assert.Equal(expectedDataToProtect, dataProtector.PlainTextToProtect);
        }
Ejemplo n.º 3
0
        public void SaveTempData(HttpContext context, IDictionary <string, object> values)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var cookieOptions = new CookieOptions()
            {
                Domain   = string.IsNullOrEmpty(_options.Value.Domain) ? null : _options.Value.Domain,
                HttpOnly = true,
                Secure   = context.Request.IsHttps,
            };

            SetCookiePath(context, cookieOptions);

            var hasValues = (values != null && values.Count > 0);

            if (hasValues)
            {
                var bytes = _tempDataSerializer.Serialize(values);
                bytes = _dataProtector.Protect(bytes);
                var encodedValue = Base64UrlTextEncoder.Encode(bytes);
                _chunkingCookieManager.AppendResponseCookie(context, CookieName, encodedValue, cookieOptions);
            }
            else
            {
                _chunkingCookieManager.DeleteCookie(context, CookieName, cookieOptions);
            }
        }
Ejemplo n.º 4
0
        public void LoadTempData_Base64UrlDecodesAnd_UnprotectsData_FromCookie()
        {
            // Arrange
            var expectedValues = new Dictionary <string, object>();

            expectedValues.Add("int", 10);
            var tempDataProviderSerializer      = new TempDataSerializer();
            var expectedDataToUnprotect         = tempDataProviderSerializer.Serialize(expectedValues);
            var base64AndUrlEncodedDataInCookie = WebEncoders.Base64UrlEncode(expectedDataToUnprotect);
            var dataProtector    = new PassThroughDataProtector();
            var tempDataProvider = GetProvider(dataProtector);
            var requestCookies   = new RequestCookieCollection(new Dictionary <string, string>()
            {
                { CookieTempDataProvider.CookieName, base64AndUrlEncodedDataInCookie }
            });
            var httpContext = new Mock <HttpContext>();

            httpContext
            .Setup(hc => hc.Request.Cookies)
            .Returns(requestCookies);

            // Act
            var actualValues = tempDataProvider.LoadTempData(httpContext.Object);

            // Assert
            Assert.Equal(expectedDataToUnprotect, dataProtector.DataToUnprotect);
            Assert.Equal(expectedValues, actualValues);
        }
Ejemplo n.º 5
0
        public void SaveTempData_CustomProviderOptions_SetsCookie_WithAppropriateCookieOptions(
            string requestPathBase,
            string optionsPath,
            string optionsDomain,
            string expectedCookiePath,
            string expectedDomain)
        {
            // Arrange
            var values = new Dictionary <string, object>();

            values.Add("int", 10);
            var tempDataProviderStore = new TempDataSerializer();
            var expectedDataToProtect = tempDataProviderStore.Serialize(values);
            var expectedDataInCookie  = WebEncoders.Base64UrlEncode(expectedDataToProtect);
            var dataProtector         = new PassThroughDataProtector();
            var tempDataProvider      = GetProvider(
                dataProtector,
                new CookieTempDataProviderOptions
            {
                Cookie =
                {
                    Path   = optionsPath,
                    Domain = optionsDomain
                }
            });
            var responseCookies = new MockResponseCookieCollection();
            var httpContext     = new Mock <HttpContext>();

            httpContext
            .SetupGet(hc => hc.Request.IsHttps)
            .Returns(false);
            httpContext
            .SetupGet(hc => hc.Request.PathBase)
            .Returns(requestPathBase);
            httpContext
            .Setup(hc => hc.Response.Cookies)
            .Returns(responseCookies);

            // Act
            tempDataProvider.SaveTempData(httpContext.Object, values);

            // Assert
            Assert.Equal(1, responseCookies.Count);
            var cookieInfo = responseCookies[CookieTempDataProvider.CookieName];

            Assert.NotNull(cookieInfo);
            Assert.Equal(expectedDataInCookie, cookieInfo.Value);
            Assert.Equal(expectedDataToProtect, dataProtector.PlainTextToProtect);
            Assert.Equal(expectedCookiePath, cookieInfo.Options.Path);
            Assert.Equal(expectedDomain, cookieInfo.Options.Domain);
            Assert.False(cookieInfo.Options.Secure);
            Assert.True(cookieInfo.Options.HttpOnly);
            Assert.Null(cookieInfo.Options.Expires);
        }
Ejemplo n.º 6
0
        public void SaveTempData_HonorsCookieSecurePolicy_OnOptions(
            bool isRequestSecure,
            CookieSecurePolicy cookieSecurePolicy,
            bool expectedSecureFlag)
        {
            // Arrange
            var values = new Dictionary <string, object>();

            values.Add("int", 10);
            var tempDataProviderStore = new TempDataSerializer();
            var expectedDataToProtect = tempDataProviderStore.Serialize(values);
            var expectedDataInCookie  = WebEncoders.Base64UrlEncode(expectedDataToProtect);
            var dataProtector         = new PassThroughDataProtector();
            var options = new CookieTempDataProviderOptions();

            options.Cookie.SecurePolicy = cookieSecurePolicy;
            var tempDataProvider = GetProvider(dataProtector, options);
            var responseCookies  = new MockResponseCookieCollection();
            var httpContext      = new Mock <HttpContext>();

            httpContext
            .SetupGet(hc => hc.Request.PathBase)
            .Returns("/");
            httpContext
            .SetupGet(hc => hc.Request.IsHttps)
            .Returns(isRequestSecure);
            httpContext
            .Setup(hc => hc.Response.Cookies)
            .Returns(responseCookies);

            // Act
            tempDataProvider.SaveTempData(httpContext.Object, values);

            // Assert
            Assert.Equal(1, responseCookies.Count);
            var cookieInfo = responseCookies[CookieTempDataProvider.CookieName];

            Assert.NotNull(cookieInfo);
            Assert.Equal(expectedDataInCookie, cookieInfo.Value);
            Assert.Equal(expectedDataToProtect, dataProtector.PlainTextToProtect);
            Assert.Equal("/", cookieInfo.Options.Path);
            Assert.Equal(expectedSecureFlag, cookieInfo.Options.Secure);
            Assert.True(cookieInfo.Options.HttpOnly);
            Assert.Null(cookieInfo.Options.Expires);
            Assert.Null(cookieInfo.Options.Domain);
        }
Ejemplo n.º 7
0
        public void SaveTempData_RemovesCookie_WhenNoDataToSave()
        {
            // Arrange
            var values = new Dictionary <string, object>();

            values.Add("int", 10);
            var tempDataProviderStore   = new TempDataSerializer();
            var serializedData          = tempDataProviderStore.Serialize(values);
            var base64AndUrlEncodedData = WebEncoders.Base64UrlEncode(serializedData);
            var dataProtector           = new PassThroughDataProtector();
            var tempDataProvider        = GetProvider(dataProtector);
            var requestCookies          = new RequestCookieCollection(new Dictionary <string, string>()
            {
                { CookieTempDataProvider.CookieName, base64AndUrlEncodedData }
            });
            var responseCookies = new MockResponseCookieCollection();
            var httpContext     = new Mock <HttpContext>();

            httpContext
            .SetupGet(hc => hc.Request.PathBase)
            .Returns("/");
            httpContext
            .Setup(hc => hc.Request.Cookies)
            .Returns(requestCookies);
            httpContext
            .Setup(hc => hc.Response.Cookies)
            .Returns(responseCookies);
            httpContext
            .Setup(hc => hc.Response.Headers)
            .Returns(new HeaderDictionary());

            // Act
            tempDataProvider.SaveTempData(httpContext.Object, new Dictionary <string, object>());

            // Assert
            Assert.Equal(1, responseCookies.Count);
            var cookie = responseCookies[CookieTempDataProvider.CookieName];

            Assert.NotNull(cookie);
            Assert.Equal(string.Empty, cookie.Value);
            Assert.NotNull(cookie.Options.Expires);
            Assert.True(cookie.Options.Expires.Value < DateTimeOffset.Now); // expired cookie
        }
Ejemplo n.º 8
0
        public void SaveTempData_SetsSecureAttributeOnCookie_OnlyIfRequestIsSecure(bool isSecure)
        {
            // Arrange
            var values = new Dictionary <string, object>();

            values.Add("int", 10);
            var tempDataProviderStore = new TempDataSerializer();
            var expectedDataToProtect = tempDataProviderStore.Serialize(values);
            var expectedDataInCookie  = Base64UrlTextEncoder.Encode(expectedDataToProtect);
            var dataProtector         = new PassThroughDataProtector();
            var tempDataProvider      = GetProvider(dataProtector);
            var responseCookies       = new MockResponseCookieCollection();
            var httpContext           = new Mock <HttpContext>();

            httpContext
            .SetupGet(hc => hc.Request.PathBase)
            .Returns("/");
            httpContext
            .SetupGet(hc => hc.Request.IsHttps)
            .Returns(isSecure);
            httpContext
            .Setup(hc => hc.Response.Cookies)
            .Returns(responseCookies);

            // Act
            tempDataProvider.SaveTempData(httpContext.Object, values);

            // Assert
            Assert.Equal(1, responseCookies.Count);
            var cookieInfo = responseCookies[CookieTempDataProvider.CookieName];

            Assert.NotNull(cookieInfo);
            Assert.Equal(expectedDataInCookie, cookieInfo.Value);
            Assert.Equal(expectedDataToProtect, dataProtector.PlainTextToProtect);
            Assert.Equal("/", cookieInfo.Options.Path);
            Assert.Equal(isSecure, cookieInfo.Options.Secure);
            Assert.True(cookieInfo.Options.HttpOnly);
            Assert.Null(cookieInfo.Options.Expires);
            Assert.Null(cookieInfo.Options.Domain);
        }
Ejemplo n.º 9
0
        public void SaveTempData(HttpContext context, IDictionary <string, object> values)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            // Accessing Session property will throw if the session middleware is not enabled.
            var session       = context.Session;
            var cookieOptions = _options.Cookie.Build(context);

            SetCookiePath(context, cookieOptions);

            var hasValues = (values != null && values.Count > 0);

            if (hasValues)
            {
                var bytes = _tempDataSerializer.Serialize(values);
                if (bytes.Length > 4096)
                {
                    session.Set(TempDataSessionStateKey, bytes);
                }
                else
                {
                    bytes = _dataProtector.Protect(bytes);
                    var encodedValue = WebEncoders.Base64UrlEncode(bytes);
                    _chunkingCookieManager.AppendResponseCookie(context, _cookieName, encodedValue, cookieOptions);
                }
            }
            else
            {
                session.Remove(TempDataSessionStateKey);

                if (context.Request.Cookies.ContainsKey(_cookieName))
                {
                    _chunkingCookieManager.DeleteCookie(context, _cookieName, cookieOptions);
                }
            }
        }
    /// <inheritdoc />
    public virtual void SaveTempData(HttpContext context, IDictionary <string, object> values)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        // Accessing Session property will throw if the session middleware is not enabled.
        var session = context.Session;

        var hasValues = (values != null && values.Count > 0);

        if (hasValues)
        {
            var bytes = _tempDataSerializer.Serialize(values);
            session.Set(TempDataSessionStateKey, bytes);
        }
        else
        {
            session.Remove(TempDataSessionStateKey);
        }
    }
Ejemplo n.º 11
0
        public void LoadTempData_ReturnsEmptyDictionary_AndClearsCookie_WhenDataIsInvalid()
        {
            // Arrange
            var dataProtector = new Mock <IDataProtector>(MockBehavior.Strict);

            dataProtector
            .Setup(d => d.Unprotect(It.IsAny <byte[]>()))
            .Throws(new Exception());

            var tempDataProvider = GetProvider(dataProtector.Object);

            var inputData = new Dictionary <string, object>();

            inputData.Add("int", 10);
            var tempDataProviderSerializer      = new TempDataSerializer();
            var expectedDataToUnprotect         = tempDataProviderSerializer.Serialize(inputData);
            var base64AndUrlEncodedDataInCookie = WebEncoders.Base64UrlEncode(expectedDataToUnprotect);

            var context = new DefaultHttpContext();

            context.Request.Cookies = new RequestCookieCollection(new Dictionary <string, string>()
            {
                { CookieTempDataProvider.CookieName, base64AndUrlEncodedDataInCookie }
            });

            // Act
            var tempDataDictionary = tempDataProvider.LoadTempData(context);

            // Assert
            Assert.Empty(tempDataDictionary);

            var setCookieHeader = SetCookieHeaderValue.Parse(context.Response.Headers["Set-Cookie"].ToString());

            Assert.Equal(CookieTempDataProvider.CookieName, setCookieHeader.Name.ToString());
            Assert.Equal(string.Empty, setCookieHeader.Value.ToString());
        }
Ejemplo n.º 12
0
        public void SaveTempData_UsesCookieName_FromOptions()
        {
            // Arrange
            var expectedCookieName = "TestCookieName";
            var values             = new Dictionary <string, object>();

            values.Add("int", 10);

            var tempDataProviderStore = new TempDataSerializer();
            var expectedDataToProtect = tempDataProviderStore.Serialize(values);
            var expectedDataInCookie  = WebEncoders.Base64UrlEncode(expectedDataToProtect);
            var tempDataProvider      = GetProvider(dataProtector: null, options: new CookieTempDataProviderOptions()
            {
                Cookie = { Name = expectedCookieName }
            });

            var responseCookies = new MockResponseCookieCollection();
            var httpContext     = new Mock <HttpContext>();

            httpContext
            .SetupGet(hc => hc.Request.PathBase)
            .Returns("/");
            httpContext
            .Setup(hc => hc.Response.Cookies)
            .Returns(responseCookies);

            // Act
            tempDataProvider.SaveTempData(httpContext.Object, values);

            // Assert
            Assert.Contains(responseCookies, (cookie) => cookie.Key == expectedCookieName);
            var cookieInfo = responseCookies[expectedCookieName];

            Assert.Equal(expectedDataInCookie, cookieInfo.Value);
            Assert.Equal("/", cookieInfo.Options.Path);
        }