예제 #1
0
        public void TokenCleanup()
        {
            IPersistedGrantStore store = Fixture.GetService <IPersistedGrantStore>();
            IHostedService       svc   = Fixture.GetService <IHostedService>();

            Client client = CreateClient();

            Provider.AddClientAsync(client).Wait();

            svc.StartAsync(default(CancellationToken)).Wait();

            PersistedGrant grant1 = CreateGrant(client.ClientId, "aaa", "t1");
            PersistedGrant grant2 = CreateGrant(client.ClientId, "aaa");

            grant1.Expiration = DateTime.Now.Add(TimeSpan.FromSeconds(15));
            grant2.Expiration = DateTime.Now.Add(TimeSpan.FromSeconds(25));

            store.StoreAsync(grant1).Wait();
            store.StoreAsync(grant2).Wait();

            List <PersistedGrant> results = store.GetAllAsync("aaa").Result?.ToList();

            Assert.Equal(2, results.Count);

            Task.Delay(20000).Wait();

            results = store.GetAllAsync("aaa").Result?.ToList();
            Assert.Equal(1, results.Count);

            Task.Delay(10000).Wait();

            results = store.GetAllAsync("aaa").Result?.ToList();
            Assert.Equal(0, results.Count);
        }
예제 #2
0
        public async Task Store_Grant_And_Retrieve_It()
        {
            var key = Guid.NewGuid().ToString("N");

            var grant = new IdentityServer4.Models.PersistedGrant
            {
                Key          = key,
                Expiration   = DateTime.UtcNow.AddDays(1),
                Type         = "test",
                ClientId     = "client1",
                SubjectId    = "sub1",
                SessionId    = "session1",
                CreationTime = DateTime.UtcNow,
                Description  = "des",
                Data         = "bla bla",
                ConsumedTime = DateTime.UtcNow
            };

            await persistedGrantStore.StoreAsync(grant);

            var item = await persistedGrantStore.GetAsync(key);

            item.Should().NotBeNull();
            item.Key.Should().Be(key);
            item.Type.Should().Be(grant.Type);
            item.ClientId.Should().Be(grant.ClientId);
            item.SubjectId.Should().Be(grant.SubjectId);
            item.Data.Should().Be(grant.Data);
            item.Description.Should().Be(grant.Description);
            item.SessionId.Should().Be(grant.SessionId);
            item.CreationTime.Should().NotBe(new DateTime());
            item.Expiration.Should().NotBeNull();
            item.ConsumedTime.Should().NotBeNull();
        }
예제 #3
0
        public void PersistedGrantStore()
        {
            IPersistedGrantStore store = Fixture.GetService <IPersistedGrantStore>();

            Client client = CreateClient();

            Provider.AddClientAsync(client).Wait();

            PersistedGrant grant1 = CreateGrant(client.ClientId, "aaa", "t1");
            PersistedGrant grant2 = CreateGrant(client.ClientId, "aaa");
            PersistedGrant grant3 = CreateGrant(client.ClientId, "aaa");
            PersistedGrant grant4 = CreateGrant(client.ClientId);
            PersistedGrant grant5 = CreateGrant(client.ClientId);

            store.StoreAsync(grant1).Wait();
            store.StoreAsync(grant2).Wait();
            store.StoreAsync(grant3).Wait();
            store.StoreAsync(grant4).Wait();
            store.StoreAsync(grant5).Wait();

            List <PersistedGrant> results = store.GetAllAsync("aaa").Result?.ToList();

            Assert.Equal(3, results.Count);

            store.RemoveAllAsync("aaa", grant1.ClientId, "t1").Wait();

            results = store.GetAllAsync("aaa").Result?.ToList();
            Assert.Equal(2, results.Count);

            store.RemoveAllAsync("aaa", grant1.ClientId).Wait();

            results = store.GetAllAsync("aaa").Result?.ToList();
            Assert.Empty(results);

            PersistedGrant result = store.GetAsync(grant5.Key).Result;

            Assert.NotNull(result);

            store.RemoveAsync(grant5.Key);
            result = store.GetAsync(grant5.Key).Result;
            Assert.Null(result);
        }
        public async Task StoreAsync(PersistedGrant grant)
        {
            object obj;

            if (_scopedStorage.TryGetValue(Constants.ScopedRequestType.ExtensionGrantValidationContext, out obj))
            {
                var extensionGrantValidationContext = obj as ExtensionGrantValidationContext;
                if (extensionGrantValidationContext.Request.GrantType == FluffyBunny4.Constants.GrantType.TokenExchange)
                {
                    if (grant.Type != IdentityServerConstants.PersistedGrantTypes.RefreshToken)
                    {
                        var offlineAccess =
                            extensionGrantValidationContext.Request.RequestedScopes.FirstOrDefault(scope =>
                                                                                                   scope == IdentityServerConstants.StandardScopes.OfflineAccess);
                        if (offlineAccess != null)
                        {
                            // refresh_token coming. so save this access_token for later storage
                            _scopedStorage.AddOrUpdate(Constants.ScopedRequestType.AccessTokenPersistedGrant,
                                                       grant);
                            return;
                        }
                        // store access_token for later
                    }
                    else
                    {
                        _scopedStorage.TryGetValue(Constants.ScopedRequestType.AccessTokenPersistedGrant, out obj);
                        var grantStored = obj as PersistedGrant;
                        var extra       = _coreMapperAccessor.Mapper.Map <PersistedGrantExtra>(grantStored);
                        extra.RefreshTokenKey = grant.Key;
                        await _innerPersistedGrantStore.StoreAsync(extra);

                        extra = _coreMapperAccessor.Mapper.Map <PersistedGrantExtra>(grant);
                        //     extra.AccessTokenKey = grantStored.Key;
                        await _innerPersistedGrantStore.StoreAsync(extra);

                        return;
                    }
                }
            }

            await _innerPersistedGrantStore.StoreAsync(grant);
        }
        public async Task StoreAsync_WhenPersistedGrantStored_ExpectSuccess()
        {
            // Arrange
            var persistedGrant = UniquePersistedGrant;

            // Act
            await _persistedGrantStore.StoreAsync(persistedGrant);


            // Assert
            var foundPersistedGrant = await _persistedGrantStore.GetAsync(persistedGrant.Key);

            // Assert
            Assert.IsNotNull(foundPersistedGrant);
        }
예제 #6
0
    public async Task StoreAsync_Should_Store_PersistedGrant()
    {
        //Act
        await _persistedGrantStore.StoreAsync(new PersistedGrant
        {
            Key          = "39",
            ClientId     = "TestClientId-39",
            Type         = "TestType-39",
            SubjectId    = "TestSubject",
            Data         = "TestData-39",
            Expiration   = new DateTime(2018, 1, 6, 21, 22, 23),
            CreationTime = new DateTime(2018, 1, 5, 19, 20, 21)
        });

        //Assert
        var persistedGrant = await _persistedGrantStore.GetAsync("39");

        persistedGrant.Key.ShouldBe("39");
        persistedGrant.ClientId.ShouldBe("TestClientId-39");
        persistedGrant.Type.ShouldBe("TestType-39");
        persistedGrant.SubjectId.ShouldBe("TestSubject");
        persistedGrant.Data.ShouldBe("TestData-39");

        persistedGrant.Expiration.HasValue.ShouldBe(true);
        persistedGrant.Expiration.Value.Year.ShouldBe(2018);
        persistedGrant.Expiration.Value.Month.ShouldBe(1);
        persistedGrant.Expiration.Value.Day.ShouldBe(6);
        persistedGrant.Expiration.Value.Hour.ShouldBe(21);
        persistedGrant.Expiration.Value.Minute.ShouldBe(22);
        persistedGrant.Expiration.Value.Second.ShouldBe(23);

        persistedGrant.CreationTime.Year.ShouldBe(2018);
        persistedGrant.CreationTime.Month.ShouldBe(1);
        persistedGrant.CreationTime.Day.ShouldBe(5);
        persistedGrant.CreationTime.Hour.ShouldBe(19);
        persistedGrant.CreationTime.Minute.ShouldBe(20);
        persistedGrant.CreationTime.Second.ShouldBe(21);
    }
예제 #7
0
        /// <summary>
        /// Stores the item.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="item">The item.</param>
        /// <param name="clientId">The client identifier.</param>
        /// <param name="subjectId">The subject identifier.</param>
        /// <param name="created">The created.</param>
        /// <param name="expiration">The expiration.</param>
        /// <returns></returns>
        protected async Task StoreItemAsync(string key, T item, string clientId, string subjectId, DateTime created, DateTime?expiration)
        {
            key = GetHashedKey(key);

            var json = _serializer.Serialize(item);

            var grant = new PersistedGrant
            {
                Key          = key,
                Type         = _grantType,
                ClientId     = clientId,
                SubjectId    = subjectId,
                CreationTime = created,
                Expiration   = expiration,
                Data         = json
            };

            await _store.StoreAsync(grant);
        }
예제 #8
0
        async Task StoreItem <T>(string key, T item, string type, string clientId, string subjectId, DateTime created, int lifetime)
        {
            key = HashKey(key, type);

            var json = _serializer.Serialize(item);

            var grant = new PersistedGrant
            {
                Key          = key,
                Type         = type,
                ClientId     = clientId,
                SubjectId    = subjectId,
                CreationTime = created,
                Expiration   = created.AddSeconds(lifetime),
                Data         = json
            };

            await _store.StoreAsync(grant);
        }
 async Task StoreAsync(PersistedGrant persistedGrant)
 {
     await _persistedGrantStore.StoreAsync(persistedGrant);
 }
예제 #10
0
 public Task StoreAsync(PersistedGrant grant)
 {
     return(_inMemoryPersistedGrantStore.StoreAsync(grant));
 }
 public Task StoreAsync(PersistedGrant grant)
 {
     return(_persistedGrantStoreImplementation.StoreAsync(grant));
 }
예제 #12
0
        public async Task exception_store_key_null_or_whitespace()
        {
            var ttl = 100; // 2 seconds
            // Act
            var result = new Action(() =>
            {
                _currentId             = NewGuidS;
                _currentPersistedGrant = new PersistedGrant
                {
                    Key          = null,
                    ClientId     = NewGuidS,
                    CreationTime = DateTime.UtcNow,
                    SubjectId    = NewGuidS,
                    Data         = NewGuidS,
                    Expiration   = DateTime.UtcNow.AddSeconds(ttl),
                    Type         = NewGuidS
                };

                _persistedGrantStore.StoreAsync(_currentPersistedGrant).GetAwaiter().GetResult();
            });

            //Assert
            result.Should().Throw <Exception>();

            result = new Action(() =>
            {
                _currentId             = NewGuidS;
                _currentPersistedGrant = new PersistedGrant
                {
                    Key          = "    ",
                    ClientId     = NewGuidS,
                    CreationTime = DateTime.UtcNow,
                    SubjectId    = NewGuidS,
                    Data         = NewGuidS,
                    Expiration   = DateTime.UtcNow.AddSeconds(ttl),
                    Type         = NewGuidS
                };

                _persistedGrantStore.StoreAsync(_currentPersistedGrant).GetAwaiter().GetResult();
            });

            //Assert
            result.Should().Throw <Exception>();
        }
        public async Task StoreAsync(Models.PersistedGrant grant)
        {
            try
            {
                if (grant == null)
                {
                    throw new ArgumentNullException(
                              nameof(grant),
                              "grant cant be null");
                }

                await _inner.StoreAsync(grant);

                var cacheKey = Utilities.CreateCachedPersistedGrantStoreKey(grant);
                var item     = new CacheItem(grant.ToEntity())
                {
                    Tags       = Utilities.CreateCachePersistedGrantStoreTags(grant),
                    Expiration =
                        Utilities.DetermineCachePersistedGrantStoreExpiration(
                            grant, _handle.options)
                };

                var result = await _setFallBackPolicy
                             .ExecuteAsync(async() =>
                {
                    await _handle.cache.InsertAsync(cacheKey, item)
                    .ConfigureAwait(false);
                    return(true);
                }).ConfigureAwait(false);


                if (result)
                {
                    if (_debugLoggingEnabled)
                    {
                        _logger.LogDebug(
                            $"Persisted grant with key {grant.Key} " +
                            $"successfully stored");
                    }
                }
                else
                {
                    if (_errorLoggingEnabled)
                    {
                        _logger.LogError(
                            $"Caching problems with persistant store cache");
                    }
                }
            }
            catch (Exception ex)
            {
                if (_errorLoggingEnabled)
                {
                    _logger.LogError(
                        ex,
                        $"something went wrong with StoreAsync " +
                        $"for  grant key {grant.Key}");
                }
                throw;
            }
        }