public async Task CookieStopsWorkingAfterExpiration()
        {
            var clock  = new TestClock();
            var server = CreateServer(options =>
            {
                options.SystemClock       = clock;
                options.ExpireTimeSpan    = TimeSpan.FromMinutes(10);
                options.SlidingExpiration = false;
            }, SignInAsAlice);

            var transaction1 = await SendAsync(server, "http://example.com/testpath");

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            clock.Add(TimeSpan.FromMinutes(7));

            var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            clock.Add(TimeSpan.FromMinutes(7));

            var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            Assert.Null(transaction2.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));
            Assert.Null(transaction3.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));
            Assert.Null(transaction4.SetCookie);
            Assert.Null(FindClaimValue(transaction4, ClaimTypes.Name));
        }
Beispiel #2
0
        public void SlidingExpirationRenewedByAccessUntilAbsoluteExpiration()
        {
            var clock = new TestClock();
            var cache = CreateCache(clock);
            var key   = "myKey";
            var value = new object();

            var result = cache.Set(key, value, new MemoryCacheEntryOptions()
                                   .SetSlidingExpiration(TimeSpan.FromMinutes(1))
                                   .SetAbsoluteExpiration(TimeSpan.FromMinutes(2)));

            Assert.Same(value, result);

            var found = cache.TryGetValue(key, out result);

            Assert.True(found);
            Assert.Same(value, result);

            for (int i = 0; i < 7; i++)
            {
                clock.Add(TimeSpan.FromSeconds(15));

                found = cache.TryGetValue(key, out result);
                Assert.True(found);
                Assert.Same(value, result);
            }

            clock.Add(TimeSpan.FromSeconds(15));

            found = cache.TryGetValue(key, out result);
            Assert.False(found);
            Assert.Null(result);
        }
Beispiel #3
0
        public async Task DeleteExpiredCacheItems()
        {
            // Arrange
            var key            = Guid.NewGuid().ToString();
            var testClock      = new TestClock();
            var sqlServerCache = GetCache(testClock);
            await sqlServerCache.SetAsync(
                key,
                Encoding.UTF8.GetBytes("Small expiration time element"),
                new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMilliseconds(250)));

            // Act
            testClock.Add(TimeSpan.FromMilliseconds(100));

            // Assert
            var cacheItemInfo = await sqlServerCache.GetAsync(key);

            Assert.NotNull(cacheItemInfo);

            // Act
            testClock.Add(TimeSpan.FromMilliseconds(200));

            // Assert
            cacheItemInfo = await sqlServerCache.GetAsync(key);

            Assert.Null(cacheItemInfo);
        }
        public async Task GetItem_SlidingExpirationDoesNot_ExceedAbsoluteExpirationIfSet()
        {
            // Arrange
            var testClock          = new TestClock();
            var utcNow             = testClock.UtcNow;
            var slidingExpiration  = TimeSpan.FromSeconds(5);
            var absoluteExpiration = utcNow.Add(TimeSpan.FromSeconds(20));
            var key            = Guid.NewGuid().ToString();
            var sqlServerCache = await GetCacheAndConnectAsync(testClock);

            var expectedValue = Encoding.UTF8.GetBytes("Hello, World!");
            await sqlServerCache.SetAsync(
                key,
                expectedValue,
                // Set both sliding and absolute expiration
                new DistributedCacheEntryOptions()
                .SetSlidingExpiration(slidingExpiration)
                .SetAbsoluteExpiration(absoluteExpiration));

            // Act && Assert
            var cacheItemInfo = await GetCacheItemFromDatabaseAsync(key);

            Assert.NotNull(cacheItemInfo);
            Assert.Equal(utcNow.AddSeconds(5), cacheItemInfo.ExpiresAtTime);

            // Accessing item at time...
            utcNow = testClock.Add(TimeSpan.FromSeconds(5)).UtcNow;
            await AssertGetCacheItemFromDatabaseAsync(
                sqlServerCache,
                key,
                expectedValue,
                slidingExpiration,
                absoluteExpiration,
                expectedExpirationTime : utcNow.AddSeconds(5));

            // Accessing item at time...
            utcNow = testClock.Add(TimeSpan.FromSeconds(5)).UtcNow;
            await AssertGetCacheItemFromDatabaseAsync(
                sqlServerCache,
                key,
                expectedValue,
                slidingExpiration,
                absoluteExpiration,
                expectedExpirationTime : utcNow.AddSeconds(5));

            // Accessing item at time...
            utcNow = testClock.Add(TimeSpan.FromSeconds(5)).UtcNow;
            // The expiration extension must not exceed the absolute expiration
            await AssertGetCacheItemFromDatabaseAsync(
                sqlServerCache,
                key,
                expectedValue,
                slidingExpiration,
                absoluteExpiration,
                expectedExpirationTime : absoluteExpiration);
        }
Beispiel #5
0
    public async Task CanAccessOldPrincipalDuringSecurityStampReplacement(bool testCore)
    {
        var clock  = new TestClock();
        var server = await CreateServer(services =>
        {
            services.Configure <SecurityStampValidatorOptions>(options =>
            {
                options.OnRefreshingPrincipal = c =>
                {
                    var newId = new ClaimsIdentity();
                    newId.AddClaim(new Claim("PreviousName", c.CurrentPrincipal.Identity.Name));
                    c.NewPrincipal.AddIdentity(newId);
                    return(Task.FromResult(0));
                };
            });
            services.AddSingleton <ISystemClock>(clock);
        }, testCore : testCore);

        var transaction1 = await SendAsync(server, "http://example.com/createMe");

        Assert.Equal(HttpStatusCode.OK, transaction1.Response.StatusCode);
        Assert.Null(transaction1.SetCookie);

        var transaction2 = await SendAsync(server, "http://example.com/pwdLogin/false");

        Assert.Equal(HttpStatusCode.OK, transaction2.Response.StatusCode);
        Assert.NotNull(transaction2.SetCookie);
        Assert.DoesNotContain("; expires=", transaction2.SetCookie);

        var transaction3 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue);

        Assert.Equal("hao", FindClaimValue(transaction3, ClaimTypes.Name));
        Assert.Null(transaction3.SetCookie);

        // Make sure we don't get a new cookie yet
        clock.Add(TimeSpan.FromMinutes(10));
        var transaction4 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue);

        Assert.Equal("hao", FindClaimValue(transaction4, ClaimTypes.Name));
        Assert.Null(transaction4.SetCookie);

        // Go past SecurityStampValidation interval and ensure we get a new cookie
        clock.Add(TimeSpan.FromMinutes(21));

        var transaction5 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue);

        Assert.NotNull(transaction5.SetCookie);
        Assert.Equal("hao", FindClaimValue(transaction5, ClaimTypes.Name));
        Assert.Equal("hao", FindClaimValue(transaction5, "PreviousName"));

        // Make sure new cookie is valid
        var transaction6 = await SendAsync(server, "http://example.com/me", transaction5.CookieNameValue);

        Assert.Equal("hao", FindClaimValue(transaction6, ClaimTypes.Name));
    }
Beispiel #6
0
        public async Task CompactsToLessThanLowWatermarkUsingLRUWhenHighWatermarkExceeded()
        {
            var testClock = new TestClock();
            var cache     = new MemoryCache(new MemoryCacheOptions
            {
                Clock                = testClock,
                SizeLimit            = 10,
                CompactionPercentage = 0.3
            });

            var numEntries = 5;
            var sem        = new SemaphoreSlim(0, numEntries);

            for (var i = 0; i < numEntries; i++)
            {
                var entryOptions = new MemoryCacheEntryOptions {
                    Size = i
                };
                entryOptions.PostEvictionCallbacks.Add(new PostEvictionCallbackRegistration
                {
                    EvictionCallback = (k, v, r, s) => sem.Release(),
                    State            = null
                });
                cache.Set($"key{i}", $"value{i}", entryOptions);
                testClock.Add(TimeSpan.FromSeconds(1));
            }

            // There should be 5 items in the cache
            Assert.Equal(numEntries, cache.Count);

            cache.Set($"key{numEntries}", $"value{numEntries}", new MemoryCacheEntryOptions {
                Size = 1
            });
            testClock.Add(TimeSpan.FromSeconds(10));

            // Wait for compaction to complete
            for (var i = 0; i < 3; i++)
            {
                Assert.True(await sem.WaitAsync(TimeSpan.FromSeconds(10)));
            }

            // There should be 2 items in the cache
            Assert.Equal(2, cache.Count);
            Assert.Null(cache.Get("key0"));
            Assert.Null(cache.Get("key1"));
            Assert.Null(cache.Get("key2"));
            Assert.NotNull(cache.Get("key3"));
            Assert.NotNull(cache.Get("key4"));
            Assert.Null(cache.Get("key5"));
        }
        public async Task CookieCanBeRenewedByValidator()
        {
            var clock  = new TestClock();
            var server = CreateServer(options =>
            {
                options.SystemClock       = clock;
                options.ExpireTimeSpan    = TimeSpan.FromMinutes(10);
                options.SlidingExpiration = false;
                options.Events            = new CookieAuthenticationEvents
                {
                    OnValidatePrincipal = ctx =>
                    {
                        ctx.ShouldRenew = true;
                        return(Task.FromResult(0));
                    }
                };
            },
                                      context =>
                                      context.Authentication.SignInAsync("Cookies",
                                                                         new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")))));

            var transaction1 = await SendAsync(server, "http://example.com/testpath");

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            Assert.NotNull(transaction2.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));

            clock.Add(TimeSpan.FromMinutes(5));

            var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction2.CookieNameValue);

            Assert.NotNull(transaction3.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));

            clock.Add(TimeSpan.FromMinutes(6));

            var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            Assert.Null(transaction4.SetCookie);
            Assert.Null(FindClaimValue(transaction4, ClaimTypes.Name));

            clock.Add(TimeSpan.FromMinutes(5));

            var transaction5 = await SendAsync(server, "http://example.com/me/Cookies", transaction2.CookieNameValue);

            Assert.Null(transaction5.SetCookie);
            Assert.Null(FindClaimValue(transaction5, ClaimTypes.Name));
        }
Beispiel #8
0
    public async Task CanCreateMeLoginAndSecurityStampExtendsExpiration(bool rememberMe, bool testCore)
    {
        var clock  = new TestClock();
        var server = await CreateServer(services => services.AddSingleton <ISystemClock>(clock), testCore : testCore);

        var transaction1 = await SendAsync(server, "http://example.com/createMe");

        Assert.Equal(HttpStatusCode.OK, transaction1.Response.StatusCode);
        Assert.Null(transaction1.SetCookie);

        var transaction2 = await SendAsync(server, "http://example.com/pwdLogin/" + rememberMe);

        Assert.Equal(HttpStatusCode.OK, transaction2.Response.StatusCode);
        Assert.NotNull(transaction2.SetCookie);
        if (rememberMe)
        {
            Assert.Contains("; expires=", transaction2.SetCookie);
        }
        else
        {
            Assert.DoesNotContain("; expires=", transaction2.SetCookie);
        }

        var transaction3 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue);

        Assert.Equal("hao", FindClaimValue(transaction3, ClaimTypes.Name));
        Assert.Null(transaction3.SetCookie);

        // Make sure we don't get a new cookie yet
        clock.Add(TimeSpan.FromMinutes(10));
        var transaction4 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue);

        Assert.Equal("hao", FindClaimValue(transaction4, ClaimTypes.Name));
        Assert.Null(transaction4.SetCookie);

        // Go past SecurityStampValidation interval and ensure we get a new cookie
        clock.Add(TimeSpan.FromMinutes(21));

        var transaction5 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue);

        Assert.NotNull(transaction5.SetCookie);
        Assert.Equal("hao", FindClaimValue(transaction5, ClaimTypes.Name));

        // Make sure new cookie is valid
        var transaction6 = await SendAsync(server, "http://example.com/me", transaction5.CookieNameValue);

        Assert.Equal("hao", FindClaimValue(transaction6, ClaimTypes.Name));
    }
Beispiel #9
0
    public async Task TwoFactorRememberCookieVerification(bool testCore)
    {
        var clock  = new TestClock();
        var server = await CreateServer(services => services.AddSingleton <ISystemClock>(clock), testCore : testCore);

        var transaction1 = await SendAsync(server, "http://example.com/createMe");

        Assert.Equal(HttpStatusCode.OK, transaction1.Response.StatusCode);
        Assert.Null(transaction1.SetCookie);

        var transaction2 = await SendAsync(server, "http://example.com/twofactorRememeber");

        Assert.Equal(HttpStatusCode.OK, transaction2.Response.StatusCode);

        var setCookie = transaction2.SetCookie;

        Assert.Contains(IdentityConstants.TwoFactorRememberMeScheme + "=", setCookie);
        Assert.Contains("; expires=", setCookie);

        var transaction3 = await SendAsync(server, "http://example.com/isTwoFactorRememebered", transaction2.CookieNameValue);

        Assert.Equal(HttpStatusCode.OK, transaction3.Response.StatusCode);

        // Wait for validation interval
        clock.Add(TimeSpan.FromMinutes(30));

        var transaction4 = await SendAsync(server, "http://example.com/isTwoFactorRememebered", transaction2.CookieNameValue);

        Assert.Equal(HttpStatusCode.OK, transaction4.Response.StatusCode);
    }
        public void AbsoluteExpiration_WorksAcrossLink()
        {
            var clock = new TestClock();
            var cache = CreateCache(clock);
            var obj = new object();
            string key = "myKey";
            string key1 = "myKey1";
            var expirationToken = new TestExpirationToken() { ActiveChangeCallbacks = true };

            using (var link = cache.CreateLinkingScope())
            {
                cache.Set(key, obj, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromSeconds(5)));

                cache.Set(key1, obj, new MemoryCacheEntryOptions().AddEntryLink(link));
            }

            Assert.Same(obj, cache.Get(key));
            Assert.Same(obj, cache.Get(key1));

            clock.Add(TimeSpan.FromSeconds(10));

            object value;
            Assert.False(cache.TryGetValue(key1, out value));
            Assert.False(cache.TryGetValue(key, out value));
        }
        public async Task SetWithSlidingExpiration_ExtendsExpirationTime(int accessItemAt, int expected)
        {
            // Arrange
            var testClock = new TestClock();
            var slidingExpirationWindow = TimeSpan.FromSeconds(10);
            var key            = Guid.NewGuid().ToString();
            var sqlServerCache = await GetCacheAndConnectAsync(testClock);

            var expectedValue          = Encoding.UTF8.GetBytes("Hello, World!");
            var expectedExpirationTime = testClock.UtcNow.AddSeconds(expected);
            await sqlServerCache.SetAsync(
                key,
                expectedValue,
                new DistributedCacheEntryOptions().SetSlidingExpiration(slidingExpirationWindow));

            testClock.Add(TimeSpan.FromSeconds(accessItemAt));
            // Act
            await AssertGetCacheItemFromDatabaseAsync(
                sqlServerCache,
                key,
                expectedValue,
                slidingExpirationWindow,
                absoluteExpiration : null,
                expectedExpirationTime : expectedExpirationTime);
        }
Beispiel #12
0
        public async Task ExpiredCookieWithValidatorStillExpired()
        {
            var clock  = new TestClock();
            var server = CreateServer(options =>
            {
                options.SystemClock    = clock;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
                options.Notifications  = new CookieAuthenticationNotifications
                {
                    OnValidatePrincipal = ctx =>
                    {
                        ctx.ShouldRenew = true;
                        return(Task.FromResult(0));
                    }
                };
            },
                                      context =>
                                      context.Authentication.SignInAsync("Cookies",
                                                                         new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")))));

            var transaction1 = await SendAsync(server, "http://example.com/testpath");

            clock.Add(TimeSpan.FromMinutes(11));

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            transaction2.SetCookie.ShouldBe(null);
            FindClaimValue(transaction2, ClaimTypes.Name).ShouldBe(null);
        }
        public void AbsoluteExpiration_WorksAcrossLink(bool trackLinkedCacheEntries)
        {
            var    clock           = new TestClock();
            var    cache           = CreateCache(clock, trackLinkedCacheEntries);
            var    obj             = new object();
            string key             = "myKey";
            string key1            = "myKey1";
            var    expirationToken = new TestExpirationToken()
            {
                ActiveChangeCallbacks = true
            };

            using (var entry = cache.CreateEntry(key))
            {
                entry.SetValue(obj);
                cache.Set(key1, obj, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromSeconds(5)));
            }

            Assert.Same(obj, cache.Get(key));
            Assert.Same(obj, cache.Get(key1));

            clock.Add(TimeSpan.FromSeconds(10));

            Assert.False(cache.TryGetValue(key1, out object value));
            Assert.Equal(!trackLinkedCacheEntries, cache.TryGetValue(key, out value));
        }
        public async Task RefreshItem_ExtendsExpirationTime_ForSlidingExpiration()
        {
            // Arrange
            var testClock         = new TestClock();
            var slidingExpiration = TimeSpan.FromSeconds(10);
            var key           = Guid.NewGuid().ToString();
            var cache         = GetSqlServerCache(GetCacheOptions(testClock));
            var expectedValue = Encoding.UTF8.GetBytes("Hello, World!");
            // The operations Set and Refresh here extend the sliding expiration 2 times.
            var expectedExpiresAtTime = testClock.UtcNow.AddSeconds(15);
            await cache.SetAsync(
                key,
                expectedValue,
                new DistributedCacheEntryOptions().SetSlidingExpiration(slidingExpiration));

            // Act
            testClock.Add(TimeSpan.FromSeconds(5));
            await cache.RefreshAsync(key);

            // Assert
            // verify if the expiration time in database is set as expected
            var cacheItemInfo = await GetCacheItemFromDatabaseAsync(key);

            Assert.NotNull(cacheItemInfo);
            Assert.Equal(slidingExpiration, cacheItemInfo.SlidingExpirationInSeconds);
            Assert.Null(cacheItemInfo.AbsoluteExpiration);
            Assert.Equal(expectedExpiresAtTime, cacheItemInfo.ExpiresAtTime);
        }
        public void AbsoluteExpiration_WorksAcrossLink()
        {
            var clock = new TestClock();
            var cache = CreateCache(clock);
            var obj = new object();
            string key = "myKey";
            string key1 = "myKey1";
            var expirationToken = new TestExpirationToken() { ActiveChangeCallbacks = true };

            using (var link = cache.CreateLinkingScope())
            {
                cache.Set(key, obj, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromSeconds(5)));

                cache.Set(key1, obj, new MemoryCacheEntryOptions().AddEntryLink(link));
            }

            Assert.Same(obj, cache.Get(key));
            Assert.Same(obj, cache.Get(key1));

            clock.Add(TimeSpan.FromSeconds(10));

            object value;
            Assert.False(cache.TryGetValue(key1, out value));
            Assert.False(cache.TryGetValue(key, out value));
        }
        public void ExpiredLazyTokenRemovesItemInBackground()
        {
            var clock = new TestClock();
            var cache = CreateCache(clock);
            string key = "myKey";
            var value = new object();
            var callbackInvoked = new ManualResetEvent(false);
            var expirationToken = new TestExpirationToken() { ActiveChangeCallbacks = false };
            cache.Set(key, value, new MemoryCacheEntryOptions()
                .AddExpirationToken(expirationToken)
                .RegisterPostEvictionCallback((subkey, subValue, reason, state) =>
            {
                // TODO: Verify params
                var localCallbackInvoked = (ManualResetEvent)state;
                localCallbackInvoked.Set();
            }, state: callbackInvoked));
            var found = cache.TryGetValue(key, out value);
            Assert.True(found);

            clock.Add(TimeSpan.FromMinutes(2));
            expirationToken.HasChanged = true;
            var ignored = cache.Get("otherKey"); // Background expiration checks are triggered by misc cache activity.
            Assert.True(callbackInvoked.WaitOne(TimeSpan.FromSeconds(30)), "Callback");

            found = cache.TryGetValue(key, out value);
            Assert.False(found);
        }
        public void ExpiredLazyTokenRemovesItemInBackground()
        {
            var    clock           = new TestClock();
            var    cache           = CreateCache(clock);
            string key             = "myKey";
            var    value           = new object();
            var    callbackInvoked = new ManualResetEvent(false);
            var    expirationToken = new TestExpirationToken()
            {
                ActiveChangeCallbacks = false
            };

            cache.Set(key, value, new MemoryCacheEntryOptions()
                      .AddExpirationToken(expirationToken)
                      .RegisterPostEvictionCallback((subkey, subValue, reason, state) =>
            {
                // TODO: Verify params
                var localCallbackInvoked = (ManualResetEvent)state;
                localCallbackInvoked.Set();
            }, state: callbackInvoked));
            var found = cache.TryGetValue(key, out value);

            Assert.True(found);

            clock.Add(TimeSpan.FromMinutes(2));
            expirationToken.HasChanged = true;
            var ignored = cache.Get("otherKey"); // Background expiration checks are triggered by misc cache activity.

            Assert.True(callbackInvoked.WaitOne(TimeSpan.FromSeconds(30)), "Callback");

            found = cache.TryGetValue(key, out value);
            Assert.False(found);
        }
        public async Task DoestNotExtendsExpirationTime_ForAbsoluteExpiration()
        {
            // Arrange
            var testClock = new TestClock();
            var absoluteExpirationRelativeToNow = TimeSpan.FromSeconds(30);
            var expectedExpiresAtTime           = testClock.UtcNow.Add(absoluteExpirationRelativeToNow);
            var key           = Guid.NewGuid().ToString();
            var cache         = GetSqlServerCache(GetCacheOptions(testClock));
            var expectedValue = Encoding.UTF8.GetBytes("Hello, World!");
            await cache.SetAsync(
                key,
                expectedValue,
                new DistributedCacheEntryOptions().SetAbsoluteExpiration(absoluteExpirationRelativeToNow));

            testClock.Add(TimeSpan.FromSeconds(25));

            // Act
            var value = await cache.GetAsync(key);

            // Assert
            Assert.NotNull(value);
            Assert.Equal(expectedValue, value);

            // verify if the expiration time in database is set as expected
            var cacheItemInfo = await GetCacheItemFromDatabaseAsync(key);

            Assert.NotNull(cacheItemInfo);
            Assert.Equal(expectedExpiresAtTime, cacheItemInfo.ExpiresAtTime);
        }
Beispiel #19
0
        public void SlidingExpirationRenewedByAccess()
        {
            var clock = new TestClock();
            var cache = CreateCache(clock);
            var key   = "myKey";
            var obj   = new object();

            var result = cache.Set(key, context =>
            {
                context.SetSlidingExpiration(TimeSpan.FromMinutes(1));
                return(obj);
            });

            Assert.Same(obj, result);

            var found = cache.TryGetValue(key, out result);

            Assert.True(found);
            Assert.Same(obj, result);

            for (int i = 0; i < 10; i++)
            {
                clock.Add(TimeSpan.FromSeconds(15));

                found = cache.TryGetValue(key, out result);
                Assert.True(found);
                Assert.Same(obj, result);
            }
        }
Beispiel #20
0
        public void AbsoluteExpirationExpires()
        {
            var clock = new TestClock();
            var cache = CreateCache(clock);
            var key   = "myKey";
            var obj   = new object();

            var result = cache.Set(key, context =>
            {
                context.SetAbsoluteExpiration(clock.UtcNow + TimeSpan.FromMinutes(1));
                return(obj);
            });

            Assert.Same(obj, result);

            var found = cache.TryGetValue(key, out result);

            Assert.True(found);
            Assert.Same(obj, result);

            clock.Add(TimeSpan.FromMinutes(2));

            found = cache.TryGetValue(key, out result);
            Assert.False(found);
            Assert.Null(result);
        }
        public async Task SetWithSlidingExpirationAndAbsoluteExpiration_ReturnsNullValue_ForExpiredCacheItem(
            int accessItemAt)
        {
            // Arrange
            var testClock          = new TestClock();
            var utcNow             = testClock.UtcNow;
            var slidingExpiration  = TimeSpan.FromSeconds(5);
            var absoluteExpiration = utcNow.Add(TimeSpan.FromSeconds(20));
            var key           = Guid.NewGuid().ToString();
            var cache         = GetSqlServerCache(GetCacheOptions(testClock));
            var expectedValue = Encoding.UTF8.GetBytes("Hello, World!");
            await cache.SetAsync(
                key,
                expectedValue,
                // Set both sliding and absolute expiration
                new DistributedCacheEntryOptions()
                .SetSlidingExpiration(slidingExpiration)
                .SetAbsoluteExpiration(absoluteExpiration));

            // Act
            utcNow = testClock.Add(TimeSpan.FromSeconds(accessItemAt)).UtcNow;
            var value = await cache.GetAsync(key);

            // Assert
            Assert.Null(value);
        }
        public void AbsoluteExpiration_WorksAcrossNestedLink()
        {
            var    clock           = new TestClock();
            var    cache           = CreateCache(clock);
            var    obj             = new object();
            string key1            = "myKey1";
            string key2            = "myKey2";
            var    expirationToken = new TestExpirationToken()
            {
                ActiveChangeCallbacks = true
            };

            using (var entry1 = cache.CreateEntry(key1))
            {
                entry1.SetValue(obj);

                using (var entry2 = cache.CreateEntry(key2))
                {
                    entry2.SetValue(obj);
                    entry2.SetAbsoluteExpiration(TimeSpan.FromSeconds(5));
                }
            }

            Assert.Same(obj, cache.Get(key1));
            Assert.Same(obj, cache.Get(key2));

            clock.Add(TimeSpan.FromSeconds(10));

            Assert.False(cache.TryGetValue(key1, out object value));
            Assert.False(cache.TryGetValue(key2, out value));
        }
Beispiel #23
0
        public void AbsoluteExpirationExpiresInBackground()
        {
            var clock           = new TestClock();
            var cache           = CreateCache(clock);
            var key             = "myKey";
            var value           = new object();
            var callbackInvoked = new ManualResetEvent(false);

            var options = new MemoryCacheEntryOptions()
                          .SetAbsoluteExpiration(clock.UtcNow + TimeSpan.FromMinutes(1))
                          .RegisterPostEvictionCallback((subkey, subValue, reason, state) =>
            {
                // TODO: Verify params
                var localCallbackInvoked = (ManualResetEvent)state;
                localCallbackInvoked.Set();
            }, callbackInvoked);
            var result = cache.Set(key, value, options);

            Assert.Same(value, result);

            var found = cache.TryGetValue(key, out result);

            Assert.True(found);
            Assert.Same(value, result);

            clock.Add(TimeSpan.FromMinutes(2));
            var ignored = cache.Get("otherKey"); // Background expiration checks are triggered by misc cache activity.

            Assert.True(callbackInvoked.WaitOne(TimeSpan.FromSeconds(30)), "Callback");

            found = cache.TryGetValue(key, out result);
            Assert.False(found);
            Assert.Null(result);
        }
Beispiel #24
0
        public async Task RefreshesSession_WhenSessionData_IsNotModified()
        {
            var clock   = new TestClock();
            var builder = new WebHostBuilder()
                          .Configure(app =>
            {
                app.UseSession();
                app.Run(context =>
                {
                    string responseData = string.Empty;
                    if (context.Request.Path == new PathString("/AddDataToSession"))
                    {
                        context.Session.SetInt32("Key", 10);
                        responseData = "added data to session";
                    }
                    else if (context.Request.Path == new PathString("/AccessSessionData"))
                    {
                        var value    = context.Session.GetInt32("Key");
                        responseData = (value == null) ? "No value found in session." : value.ToString();
                    }
                    else if (context.Request.Path == new PathString("/DoNotAccessSessionData"))
                    {
                        responseData = "did not access session data";
                    }

                    return(context.Response.WriteAsync(responseData));
                });
            })
                          .ConfigureServices(services =>
            {
                services.AddSingleton(typeof(ILoggerFactory), NullLoggerFactory.Instance);
                services.AddDistributedMemoryCache();
                services.AddSession(o => o.IdleTimeout = TimeSpan.FromMinutes(20));
                services.Configure <MemoryCacheOptions>(o => o.Clock = clock);
            });

            using (var server = new TestServer(builder))
            {
                var client   = server.CreateClient();
                var response = await client.GetAsync("AddDataToSession");

                response.EnsureSuccessStatusCode();

                client = server.CreateClient();
                var cookie = SetCookieHeaderValue.ParseList(response.Headers.GetValues("Set-Cookie").ToList()).First();
                client.DefaultRequestHeaders.Add(
                    "Cookie", new CookieHeaderValue(cookie.Name, cookie.Value).ToString());

                for (var i = 0; i < 5; i++)
                {
                    clock.Add(TimeSpan.FromMinutes(10));
                    await client.GetStringAsync("/DoNotAccessSessionData");
                }

                var data = await client.GetStringAsync("/AccessSessionData");

                Assert.Equal("10", data);
            }
        }
Beispiel #25
0
        public void CompactPrioritizesLRU()
        {
            var testClock = new TestClock();
            var cache     = CreateCache(testClock);

            cache.Set("key1", "value1");
            testClock.Add(TimeSpan.FromSeconds(1));
            cache.Set("key2", "value2");
            testClock.Add(TimeSpan.FromSeconds(1));
            cache.Set("key3", "value3");
            testClock.Add(TimeSpan.FromSeconds(1));
            cache.Set("key4", "value4");
            Assert.Equal(4, cache.Count);
            cache.Compact(0.90);
            Assert.Equal(1, cache.Count);
            Assert.Equal("value4", cache.Get("key4"));
        }
Beispiel #26
0
    public async Task CanCreateMeLoginAndCookieStopsWorkingAfterExpiration(bool testCore)
    {
        var clock  = new TestClock();
        var server = await CreateServer(services =>
        {
            services.ConfigureApplicationCookie(options =>
            {
                options.ExpireTimeSpan    = TimeSpan.FromMinutes(10);
                options.SlidingExpiration = false;
            });
            services.AddSingleton <ISystemClock>(clock);
        }, testCore : testCore);

        var transaction1 = await SendAsync(server, "http://example.com/createMe");

        Assert.Equal(HttpStatusCode.OK, transaction1.Response.StatusCode);
        Assert.Null(transaction1.SetCookie);

        var transaction2 = await SendAsync(server, "http://example.com/pwdLogin/false");

        Assert.Equal(HttpStatusCode.OK, transaction2.Response.StatusCode);
        Assert.NotNull(transaction2.SetCookie);
        Assert.DoesNotContain("; expires=", transaction2.SetCookie);

        var transaction3 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue);

        Assert.Equal("hao", FindClaimValue(transaction3, ClaimTypes.Name));
        Assert.Null(transaction3.SetCookie);

        clock.Add(TimeSpan.FromMinutes(7));

        var transaction4 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue);

        Assert.Equal("hao", FindClaimValue(transaction4, ClaimTypes.Name));
        Assert.Null(transaction4.SetCookie);

        clock.Add(TimeSpan.FromMinutes(7));

        var transaction5 = await SendAsync(server, "http://example.com/me", transaction2.CookieNameValue);

        Assert.Null(FindClaimValue(transaction5, ClaimTypes.Name));
        Assert.Null(transaction5.SetCookie);
    }
        public async Task CookieExpirationCanBeOverridenInSignin()
        {
            var        clock  = new TestClock();
            TestServer server = CreateServer(options =>
            {
                options.SystemClock       = clock;
                options.ExpireTimeSpan    = TimeSpan.FromMinutes(10);
                options.SlidingExpiration = false;
            },
                                             context =>
            {
                context.Response.SignIn(
                    new AuthenticationProperties()
                {
                    ExpiresUtc = clock.UtcNow.Add(TimeSpan.FromMinutes(5))
                },
                    new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")));
                return(Task.FromResult <object>(null));
            });

            Transaction transaction1 = await SendAsync(server, "http://example.com/testpath");

            Transaction transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            clock.Add(TimeSpan.FromMinutes(3));

            Transaction transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            clock.Add(TimeSpan.FromMinutes(3));

            Transaction transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            transaction2.SetCookie.ShouldBe(null);
            FindClaimValue(transaction2, ClaimTypes.Name).ShouldBe("Alice");
            transaction3.SetCookie.ShouldBe(null);
            FindClaimValue(transaction3, ClaimTypes.Name).ShouldBe("Alice");
            transaction4.SetCookie.ShouldBe(null);
            FindClaimValue(transaction4, ClaimTypes.Name).ShouldBe(null);
        }
        public async Task CookieExpirationCanBeOverridenInEvent()
        {
            var clock  = new TestClock();
            var server = CreateServer(options =>
            {
                options.SystemClock       = clock;
                options.ExpireTimeSpan    = TimeSpan.FromMinutes(10);
                options.SlidingExpiration = false;
                options.Events            = new CookieAuthenticationEvents()
                {
                    OnSigningIn = context =>
                    {
                        context.Properties.ExpiresUtc = clock.UtcNow.Add(TimeSpan.FromMinutes(5));
                        return(Task.FromResult(0));
                    }
                };
            }, SignInAsAlice);

            var transaction1 = await SendAsync(server, "http://example.com/testpath");

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            Assert.Null(transaction2.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));

            clock.Add(TimeSpan.FromMinutes(3));

            var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            Assert.Null(transaction3.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));

            clock.Add(TimeSpan.FromMinutes(3));

            var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            Assert.Null(transaction4.SetCookie);
            Assert.Null(FindClaimValue(transaction4, ClaimTypes.Name));
        }
        public async Task CookieIsRenewedWithSlidingExpiration()
        {
            var clock  = new TestClock();
            var server = CreateServer(options =>
            {
                options.SystemClock       = clock;
                options.ExpireTimeSpan    = TimeSpan.FromMinutes(10);
                options.SlidingExpiration = true;
            }, SignInAsAlice);

            var transaction1 = await SendAsync(server, "http://example.com/testpath");

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            Assert.Null(transaction2.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));

            clock.Add(TimeSpan.FromMinutes(4));

            var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            Assert.Null(transaction3.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));

            clock.Add(TimeSpan.FromMinutes(4));

            // transaction4 should arrive with a new SetCookie value
            var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            Assert.NotNull(transaction4.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction4, ClaimTypes.Name));

            clock.Add(TimeSpan.FromMinutes(4));

            var transaction5 = await SendAsync(server, "http://example.com/me/Cookies", transaction4.CookieNameValue);

            Assert.Null(transaction5.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction5, ClaimTypes.Name));
        }
        public async Task CookieExpirationCanBeOverridenInSignin()
        {
            var clock  = new TestClock();
            var server = CreateServer(options =>
            {
                options.SystemClock       = clock;
                options.ExpireTimeSpan    = TimeSpan.FromMinutes(10);
                options.SlidingExpiration = false;
            },
                                      context =>
                                      context.Authentication.SignInAsync("Cookies",
                                                                         new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"))),
                                                                         new AuthenticationProperties()
            {
                ExpiresUtc = clock.UtcNow.Add(TimeSpan.FromMinutes(5))
            }));

            var transaction1 = await SendAsync(server, "http://example.com/testpath");

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            clock.Add(TimeSpan.FromMinutes(3));

            var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            clock.Add(TimeSpan.FromMinutes(3));

            var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            Assert.Null(transaction2.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));
            Assert.Null(transaction3.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));
            Assert.Null(transaction4.SetCookie);
            Assert.Null(FindClaimValue(transaction4, ClaimTypes.Name));
        }
        public async Task CookieExpirationCanBeOverridenInEvent()
        {
            var        clock  = new TestClock();
            TestServer server = CreateServer(options =>
            {
                options.SystemClock       = clock;
                options.ExpireTimeSpan    = TimeSpan.FromMinutes(10);
                options.SlidingExpiration = false;
                options.Notifications     = new CookieAuthenticationNotifications()
                {
                    OnResponseSignIn = context =>
                    {
                        context.Properties.ExpiresUtc = clock.UtcNow.Add(TimeSpan.FromMinutes(5));
                    }
                };
            }, SignInAsAlice);

            Transaction transaction1 = await SendAsync(server, "http://example.com/testpath");

            Transaction transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            clock.Add(TimeSpan.FromMinutes(3));

            Transaction transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            clock.Add(TimeSpan.FromMinutes(3));

            Transaction transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            transaction2.SetCookie.ShouldBe(null);
            FindClaimValue(transaction2, ClaimTypes.Name).ShouldBe("Alice");
            transaction3.SetCookie.ShouldBe(null);
            FindClaimValue(transaction3, ClaimTypes.Name).ShouldBe("Alice");
            transaction4.SetCookie.ShouldBe(null);
            FindClaimValue(transaction4, ClaimTypes.Name).ShouldBe(null);
        }
        public async Task SetWithAbsoluteExpirationRelativeToNow_ReturnsNullValue_ForExpiredCacheItem()
        {
            // Arrange
            var testClock = new TestClock();
            var key       = Guid.NewGuid().ToString();
            var cache     = GetSqlServerCache(GetCacheOptions(testClock));
            await cache.SetAsync(
                key,
                Encoding.UTF8.GetBytes("Hello, World!"),
                new DistributedCacheEntryOptions().SetAbsoluteExpiration(relative: TimeSpan.FromSeconds(10)));

            // set the clock's UtcNow far in future
            testClock.Add(TimeSpan.FromHours(10));

            // Act
            var value = await cache.GetAsync(key);

            // Assert
            Assert.Null(value);
        }
Beispiel #33
0
        public async Task CookieStopsWorkingAfterExpiration()
        {
            var clock = new TestClock();
            var server = CreateServer(new CookieAuthenticationOptions
            {
                SystemClock = clock,
                ExpireTimeSpan = TimeSpan.FromMinutes(10),
                SlidingExpiration = false
            }, SignInAsAlice);

            var transaction1 = await SendAsync(server, "http://example.com/testpath");

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            clock.Add(TimeSpan.FromMinutes(7));

            var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            clock.Add(TimeSpan.FromMinutes(7));

            var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            Assert.Null(transaction2.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));
            Assert.Null(transaction3.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));
            Assert.Null(transaction4.SetCookie);
            Assert.Null(FindClaimValue(transaction4, ClaimTypes.Name));
        }
Beispiel #34
0
        public async Task CookieExpirationCanBeOverridenInSignin()
        {
            var clock = new TestClock();
            var server = CreateServer(new CookieAuthenticationOptions
            {
                SystemClock = clock,
                ExpireTimeSpan = TimeSpan.FromMinutes(10),
                SlidingExpiration = false
            },
            context =>
                context.Authentication.SignInAsync("Cookies",
                    new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"))),
                    new AuthenticationProperties() { ExpiresUtc = clock.UtcNow.Add(TimeSpan.FromMinutes(5)) }));

            var transaction1 = await SendAsync(server, "http://example.com/testpath");

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            clock.Add(TimeSpan.FromMinutes(3));

            var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            clock.Add(TimeSpan.FromMinutes(3));

            var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            Assert.Null(transaction2.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));
            Assert.Null(transaction3.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));
            Assert.Null(transaction4.SetCookie);
            Assert.Null(FindClaimValue(transaction4, ClaimTypes.Name));
        }
Beispiel #35
0
        public async Task CookieValidatorOnlyCalledOnce()
        {
            var clock = new TestClock();
            var server = CreateServer(new CookieAuthenticationOptions
            {
                SystemClock = clock,
                ExpireTimeSpan = TimeSpan.FromMinutes(10),
                SlidingExpiration = false,
                Events = new CookieAuthenticationEvents
                {
                    OnValidatePrincipal = ctx =>
                    {
                        ctx.ShouldRenew = true;
                        return Task.FromResult(0);
                    }
                }
            },
            context =>
                context.Authentication.SignInAsync("Cookies",
                    new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")))));

            var transaction1 = await SendAsync(server, "http://example.com/testpath");

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
            Assert.NotNull(transaction2.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));

            clock.Add(TimeSpan.FromMinutes(5));

            var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction2.CookieNameValue);
            Assert.NotNull(transaction3.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));

            clock.Add(TimeSpan.FromMinutes(6));

            var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
            Assert.Null(transaction4.SetCookie);
            Assert.Null(FindClaimValue(transaction4, ClaimTypes.Name));

            clock.Add(TimeSpan.FromMinutes(5));

            var transaction5 = await SendAsync(server, "http://example.com/me/Cookies", transaction2.CookieNameValue);
            Assert.Null(transaction5.SetCookie);
            Assert.Null(FindClaimValue(transaction5, ClaimTypes.Name));
        }
        public async Task CookieStopsWorkingAfterExpiration()
        {
            var clock = new TestClock();
            var server = CreateServer(options =>
            {
                options.SystemClock = clock;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
                options.SlidingExpiration = false;
            }, SignInAsAlice);

            var transaction1 = await SendAsync(server, "http://example.com/testpath");

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            clock.Add(TimeSpan.FromMinutes(7));

            var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            clock.Add(TimeSpan.FromMinutes(7));

            var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            transaction2.SetCookie.ShouldBe(null);
            FindClaimValue(transaction2, ClaimTypes.Name).ShouldBe("Alice");
            transaction3.SetCookie.ShouldBe(null);
            FindClaimValue(transaction3, ClaimTypes.Name).ShouldBe("Alice");
            transaction4.SetCookie.ShouldBe(null);
            FindClaimValue(transaction4, ClaimTypes.Name).ShouldBe(null);
        }
Beispiel #37
0
        public async Task ShouldRenewUpdatesIssuedExpiredUtc(bool sliding)
        {
            var clock = new TestClock();
            DateTimeOffset? lastValidateIssuedDate = null;
            DateTimeOffset? lastExpiresDate = null;
            var server = CreateServer(new CookieAuthenticationOptions
            {
                SystemClock = clock,
                ExpireTimeSpan = TimeSpan.FromMinutes(10),
                SlidingExpiration = sliding,
                Events = new CookieAuthenticationEvents
                {
                    OnValidatePrincipal = ctx =>
                    {
                        lastValidateIssuedDate = ctx.Properties.IssuedUtc;
                        lastExpiresDate = ctx.Properties.ExpiresUtc;
                        ctx.ShouldRenew = true;
                        return Task.FromResult(0);
                    }
                }
            },
            context =>
                context.Authentication.SignInAsync("Cookies",
                    new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")))));

            var transaction1 = await SendAsync(server, "http://example.com/testpath");

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
            Assert.NotNull(transaction2.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));

            Assert.NotNull(lastValidateIssuedDate);
            Assert.NotNull(lastExpiresDate);

            var firstIssueDate = lastValidateIssuedDate;
            var firstExpiresDate = lastExpiresDate;

            clock.Add(TimeSpan.FromMinutes(1));

            var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction2.CookieNameValue);
            Assert.NotNull(transaction3.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));

            clock.Add(TimeSpan.FromMinutes(2));

            var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction3.CookieNameValue);
            Assert.NotNull(transaction4.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction4, ClaimTypes.Name));

            Assert.NotEqual(lastValidateIssuedDate, firstIssueDate);
            Assert.NotEqual(firstExpiresDate, lastExpiresDate);
        }
Beispiel #38
0
        public async Task CookieExpirationCanBeOverridenInEvent()
        {
            var clock = new TestClock();
            var server = CreateServer(new CookieAuthenticationOptions
            {
                SystemClock = clock,
                ExpireTimeSpan = TimeSpan.FromMinutes(10),
                SlidingExpiration = false,
                Events = new CookieAuthenticationEvents()
                {
                    OnSigningIn = context =>
                    {
                        context.Properties.ExpiresUtc = clock.UtcNow.Add(TimeSpan.FromMinutes(5));
                        return Task.FromResult(0);
                    }
                }
            }, SignInAsAlice);

            var transaction1 = await SendAsync(server, "http://example.com/testpath");

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
            Assert.Null(transaction2.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));

            clock.Add(TimeSpan.FromMinutes(3));

            var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
            Assert.Null(transaction3.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));

            clock.Add(TimeSpan.FromMinutes(3));

            var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
            Assert.Null(transaction4.SetCookie);
            Assert.Null(FindClaimValue(transaction4, ClaimTypes.Name));
        }
Beispiel #39
0
        public async Task CookieIsRenewedWithSlidingExpiration()
        {
            var clock = new TestClock();
            var server = CreateServer(new CookieAuthenticationOptions
            {
                SystemClock = clock,
                ExpireTimeSpan = TimeSpan.FromMinutes(10),
                SlidingExpiration = true
            }, SignInAsAlice);

            var transaction1 = await SendAsync(server, "http://example.com/testpath");

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
            Assert.Null(transaction2.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction2, ClaimTypes.Name));

            clock.Add(TimeSpan.FromMinutes(4));

            var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
            Assert.Null(transaction3.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction3, ClaimTypes.Name));

            clock.Add(TimeSpan.FromMinutes(4));

            // transaction4 should arrive with a new SetCookie value
            var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
            Assert.NotNull(transaction4.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction4, ClaimTypes.Name));

            clock.Add(TimeSpan.FromMinutes(4));

            var transaction5 = await SendAsync(server, "http://example.com/me/Cookies", transaction4.CookieNameValue);
            Assert.Null(transaction5.SetCookie);
            Assert.Equal("Alice", FindClaimValue(transaction5, ClaimTypes.Name));
        }
        public async Task CookieCanBeRenewedByValidatorWithSlidingExpiry()
        {
            var clock = new TestClock();
            var server = CreateServer(options =>
            {
                options.SystemClock = clock;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
                options.Notifications = new CookieAuthenticationNotifications
                {
                    OnValidatePrincipal = ctx =>
                    {
                        ctx.ShouldRenew = true;
                        return Task.FromResult(0);
                    }
                };
            },
            context =>
                context.Authentication.SignInAsync("Cookies",
                    new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")))));

            var transaction1 = await SendAsync(server, "http://example.com/testpath");

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
            transaction2.SetCookie.ShouldNotBe(null);
            FindClaimValue(transaction2, ClaimTypes.Name).ShouldBe("Alice");

            clock.Add(TimeSpan.FromMinutes(5));

            var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction2.CookieNameValue);
            transaction3.SetCookie.ShouldNotBe(null);
            FindClaimValue(transaction3, ClaimTypes.Name).ShouldBe("Alice");

            clock.Add(TimeSpan.FromMinutes(6));

            var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction3.CookieNameValue);
            transaction4.SetCookie.ShouldNotBe(null);
            FindClaimValue(transaction4, ClaimTypes.Name).ShouldBe("Alice");

            clock.Add(TimeSpan.FromMinutes(11));

            var transaction5 = await SendAsync(server, "http://example.com/me/Cookies", transaction4.CookieNameValue);
            transaction5.SetCookie.ShouldBe(null);
            FindClaimValue(transaction5, ClaimTypes.Name).ShouldBe(null);
        }
        public async Task ExpiredCookieWithValidatorStillExpired()
        {
            var clock = new TestClock();
            var server = CreateServer(options =>
            {
                options.SystemClock = clock;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
                options.Events = new CookieAuthenticationEvents
                {
                    OnValidatePrincipal = ctx =>
                    {
                        ctx.ShouldRenew = true;
                        return Task.FromResult(0);
                    }
                };
            },
            context =>
                context.Authentication.SignInAsync("Cookies",
                    new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies")))));

            var transaction1 = await SendAsync(server, "http://example.com/testpath");

            clock.Add(TimeSpan.FromMinutes(11));

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
            Assert.Null(transaction2.SetCookie);
            Assert.Null(FindClaimValue(transaction2, ClaimTypes.Name));
        }
        public async Task CookieIsRenewedWithSlidingExpiration()
        {
            var clock = new TestClock();
            var server = CreateServer(options =>
            {
                options.SystemClock = clock;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
                options.SlidingExpiration = true;
            }, SignInAsAlice);

            var transaction1 = await SendAsync(server, "http://example.com/testpath");

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
            transaction2.SetCookie.ShouldBe(null);
            FindClaimValue(transaction2, ClaimTypes.Name).ShouldBe("Alice");

            clock.Add(TimeSpan.FromMinutes(4));

            var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
            transaction3.SetCookie.ShouldBe(null);
            FindClaimValue(transaction3, ClaimTypes.Name).ShouldBe("Alice");

            clock.Add(TimeSpan.FromMinutes(4));

            // transaction4 should arrive with a new SetCookie value
            var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
            transaction4.SetCookie.ShouldNotBe(null);
            FindClaimValue(transaction4, ClaimTypes.Name).ShouldBe("Alice");

            clock.Add(TimeSpan.FromMinutes(4));

            var transaction5 = await SendAsync(server, "http://example.com/me/Cookies", transaction4.CookieNameValue);
            transaction5.SetCookie.ShouldBe(null);
            FindClaimValue(transaction5, ClaimTypes.Name).ShouldBe("Alice");
        }
        public async Task CookieExpirationCanBeOverridenInSignin()
        {
            var clock = new TestClock();
            var server = CreateServer(options =>
            {
                options.SystemClock = clock;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
                options.SlidingExpiration = false;
            },
            context =>
            {
                context.Authentication.SignIn("Cookies",
                    new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"))),
                    new AuthenticationProperties() { ExpiresUtc = clock.UtcNow.Add(TimeSpan.FromMinutes(5)) });
                    return Task.FromResult<object>(null);
            });

            var transaction1 = await SendAsync(server, "http://example.com/testpath");

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            clock.Add(TimeSpan.FromMinutes(3));

            var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            clock.Add(TimeSpan.FromMinutes(3));

            var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);

            transaction2.SetCookie.ShouldBe(null);
            FindClaimValue(transaction2, ClaimTypes.Name).ShouldBe("Alice");
            transaction3.SetCookie.ShouldBe(null);
            FindClaimValue(transaction3, ClaimTypes.Name).ShouldBe("Alice");
            transaction4.SetCookie.ShouldBe(null);
            FindClaimValue(transaction4, ClaimTypes.Name).ShouldBe(null);
        }
        public async Task CookieExpirationCanBeOverridenInEvent()
        {
            var clock = new TestClock();
            var server = CreateServer(options =>
            {
                options.SystemClock = clock;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
                options.SlidingExpiration = false;
                options.Notifications = new CookieAuthenticationNotifications()
                {
                    OnResponseSignIn = context =>
                    {
                        context.Properties.ExpiresUtc = clock.UtcNow.Add(TimeSpan.FromMinutes(5));
                    }
                };
            }, SignInAsAlice);

            var transaction1 = await SendAsync(server, "http://example.com/testpath");

            var transaction2 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
            transaction2.SetCookie.ShouldBe(null);
            FindClaimValue(transaction2, ClaimTypes.Name).ShouldBe("Alice");

            clock.Add(TimeSpan.FromMinutes(3));

            var transaction3 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
            transaction3.SetCookie.ShouldBe(null);
            FindClaimValue(transaction3, ClaimTypes.Name).ShouldBe("Alice");

            clock.Add(TimeSpan.FromMinutes(3));

            var transaction4 = await SendAsync(server, "http://example.com/me/Cookies", transaction1.CookieNameValue);
            transaction4.SetCookie.ShouldBe(null);
            FindClaimValue(transaction4, ClaimTypes.Name).ShouldBe(null);
        }