Ejemplo n.º 1
0
        public async Task <IEnumerable <PersistedGrant> > GetAllAsync(string subjectId)
        {
            string hashedSubject = KeyGeneratorHelper.GenerateHashValue(subjectId);

            string partitionKeyFilter = TableQuery.GenerateFilterCondition("PartitionKey",
                                                                           QueryComparisons.Equal,
                                                                           hashedSubject);

            TableQuery <PersistedGrantTblEntity> tq = new TableQuery <PersistedGrantTblEntity>();

            tq.FilterString = partitionKeyFilter;

            var list = (await StorageContext.GetAllByTableQueryAsync(tq, StorageContext.PersistedGrantTable).ConfigureAwait(false))
                       .Select(s => s.ToModel()).ToArray(); //without .ToArray() error occurs.

            await Task.WhenAll(list.Select(m =>
            {
                return(StorageContext.GetBlobContentAsync(m.Key, StorageContext.PersistedGrantBlobContainer)
                       .ContinueWith((blobTask) =>
                {
                    m.Data = blobTask.Result;
                }));
            }));

            _logger.LogDebug($"{list.Count()} persisted grants found for {subjectId}");
            return(list);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Generazione del token di autenticazione per l'utente specificato
        /// </summary>
        /// <param name="userId">User id dell'utente proprietario del token</param>
        /// <param name="tokenType">Tipo di token da generare</param>
        /// <param name="milliseconds">Durata del token espressa in millisecondi</param>
        /// <param name="keyLength">Lunghezza della chiave espressa in numero di caratteri</param>
        /// <param name="initializationVectorLength">Lunghezza dell'initialization vector espressa in numero di caratteri</param>
        /// <returns>Token criptato</returns>
        public override string Generate(string userId, AuthTokenManager.TokenTypeEnum tokenType, double milliseconds, AuthTokenManager.KeyLengthEnum keyLength, AuthTokenManager.KeyLengthEnum initializationVectorLength)
        {
            // Chiave privata, vettore di inizializzazione e la userid pulita
            String key, initializationVector, cleanedUserId;

            // Pulizia dello user id
            cleanedUserId = userId.Trim().ToUpper();

            // Decifratura lunghezza della chiave e dell'initialization vector
            int kLength  = this.DecodeKeyLength(keyLength);
            int ivLength = this.DecodeKeyLength(initializationVectorLength);

            // Generazione della chiavi
            key = KeyGeneratorHelper.BetterRandomString(kLength);
            initializationVector = KeyGeneratorHelper.BetterRandomString(ivLength);

            try
            {
                CryptoString crypto       = new CryptoString(key, initializationVector);
                string       encodedValue = crypto.Encrypt(String.Format(ENCRYPTED_VALUE_FORMAT, cleanedUserId, GetSessionId(), this.GetActualDateFromDB(), tokenType, this.GetExpirationDate(tokenType, milliseconds)));

                // Salvataggio token su db
                this.SaveToken(key, encodedValue, initializationVector, cleanedUserId);

                return(string.Format("{0}{1}", TOKEN_PREFIX, encodedValue));
            }
            catch (Exception ex)
            {
                throw new EncryptionException(ex);
            }
        }
        private string GetTableFilter(PersistedGrantFilter grantFilter)
        {
            string hashedSubject = KeyGeneratorHelper.GenerateHashValue(grantFilter.SubjectId);

            string tableFilter = TableQuery.GenerateFilterCondition(nameof(PersistedGrantTblEntity.PartitionKey),
                                                                    QueryComparisons.Equal,
                                                                    hashedSubject);

            if (!String.IsNullOrWhiteSpace(grantFilter.ClientId))
            {
                string rowClientFilter = TableQuery.GenerateFilterCondition(nameof(PersistedGrantTblEntity.ClientId),
                                                                            QueryComparisons.Equal,
                                                                            grantFilter.ClientId);
                tableFilter = TableQuery.CombineFilters(tableFilter, TableOperators.And, rowClientFilter);
            }

            if (!String.IsNullOrWhiteSpace(grantFilter.Type))
            {
                string rowTypeFilter = TableQuery.GenerateFilterCondition(nameof(PersistedGrantTblEntity.Type),
                                                                          QueryComparisons.Equal,
                                                                          grantFilter.Type);
                tableFilter = TableQuery.CombineFilters(tableFilter, TableOperators.And, rowTypeFilter);
            }

            if (!String.IsNullOrWhiteSpace(grantFilter.SessionId))
            {
                string rowSessionIdFilter = TableQuery.GenerateFilterCondition(nameof(PersistedGrantTblEntity.SessionId),
                                                                               QueryComparisons.Equal,
                                                                               grantFilter.SessionId);
                tableFilter = TableQuery.CombineFilters(tableFilter, TableOperators.And, rowSessionIdFilter);
            }

            return(tableFilter);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Get table entity where the partition and row key are the hash of the entity key provided
        /// </summary>
        /// <typeparam name="Entity"></typeparam>
        /// <param name="keyNotHashed">Key of the entity (not hashed)</param>
        /// <returns></returns>
        public async Task <Entity> GetEntityTableAsync <Entity>(string keyNotHashed, CloudTable table)
            where Entity : class, ITableEntity, new()
        {
            string hashedKey = KeyGeneratorHelper.GenerateHashValue(keyNotHashed);
            var    r         = await table.ExecuteAsync(TableOperation.Retrieve <Entity>(hashedKey, hashedKey));

            return(r.Result as Entity);
        }
        public async Task RemoveAllAsync(string subjectId, string clientId, string type)
        {
            CloudTable table = StorageContext.PersistedGrantTable;

            string hashedSubject = KeyGeneratorHelper.GenerateHashValue(subjectId);

            string partitionKeyFilter = TableQuery.GenerateFilterCondition("PartitionKey",
                                                                           QueryComparisons.Equal,
                                                                           hashedSubject);

            string rowClientFilter = TableQuery.GenerateFilterCondition("ClientId",
                                                                        QueryComparisons.Equal,
                                                                        clientId);

            string rowTypeFilter = TableQuery.GenerateFilterCondition("Type",
                                                                      QueryComparisons.Equal,
                                                                      type);

            string rowFilter = TableQuery.CombineFilters(rowClientFilter, TableOperators.And, rowTypeFilter);

            string filter = TableQuery.CombineFilters(partitionKeyFilter, TableOperators.And, rowFilter);

            TableQuery <PersistedGrantTblEntity> tq = new TableQuery <PersistedGrantTblEntity>();

            tq.FilterString = filter;

            var entities = await StorageContext.GetAllByTableQueryAsync(tq, StorageContext.PersistedGrantTable);

            int count = entities.Count();

            _logger.LogDebug("removing {persistedGrantCount} persisted grants from database for subject {subjectId}, clientId {clientId}, grantType {persistedGrantType}", count, subjectId, clientId, type);

            List <Task> mainTasks = new List <Task>(count * 3);

            foreach (var subjectEntity in entities)
            {
                var deletes = subjectEntity.ToModel().ToEntities();
                mainTasks.Add(StorageContext.GetAndDeleteTableEntityByKeys(deletes.keyGrant.PartitionKey, deletes.keyGrant.RowKey, StorageContext.PersistedGrantTable));
                mainTasks.Add(table.ExecuteAsync(TableOperation.Delete(subjectEntity)));
                mainTasks.Add(StorageContext.DeleteBlobAsync(subjectEntity.Key, StorageContext.PersistedGrantBlobContainer));
            }

            try
            {
                await Task.WhenAll(mainTasks);
            }
            catch (AggregateException agg)
            {
                ExceptionHelper.LogStorageExceptions(agg, (tableEx) =>
                {
                    _logger.LogDebug("removing {persistedGrantCount} persisted grants from table storage for subject {subjectId}, clientId {clientId}", count, subjectId, clientId);
                }, (blobEx) =>
                {
                    _logger.LogDebug("removing {persistedGrantCount} persisted grants from blob storage for subject {subjectId}, clientId {clientId}", count, subjectId, clientId);
                });
            }
        }
Ejemplo n.º 6
0
 private Entities.ResourceScopeIndexTblEntity GenerateResourceIndexEntity(string name, string scope)
 {
     return(new Entities.ResourceScopeIndexTblEntity()
     {
         PartitionKey = KeyGeneratorHelper.GenerateHashValue(scope),
         RowKey = KeyGeneratorHelper.GenerateHashValue(name),
         ResourceName = name,
         ScopeName = scope,
         ETag = KeyGeneratorHelper.ETagWildCard
     });
 }
Ejemplo n.º 7
0
        private async Task <List <Entities.ResourceScopeIndexTblEntity> > GetResourceScopeIndexTblEntitiesAsync(string scope, CloudTable table)
        {
            string partitionKeyFilter = TableQuery.GenerateFilterCondition("PartitionKey",
                                                                           QueryComparisons.Equal,
                                                                           KeyGeneratorHelper.GenerateHashValue(scope));

            TableQuery <Entities.ResourceScopeIndexTblEntity> tq = new TableQuery <Entities.ResourceScopeIndexTblEntity>();

            tq.FilterString = partitionKeyFilter;

            return((await StorageContext.GetAllByTableQueryAsync(tq, table))?.ToList());
        }
        static PersistedGrantMappers()
        {
            KeyMapperConfiguration = new MapperConfiguration((cfg) =>
            {
                cfg.CreateMap <PersistedGrant, PersistedGrantTblEntity>()
                .ForMember(dest => dest.RowKey,
                           opt => {
                    opt.MapFrom(src => KeyGeneratorHelper.GenerateHashValue(src.Key));
                })
                .ForMember(dest => dest.PartitionKey,
                           opt => {
                    opt.MapFrom(src => KeyGeneratorHelper.GenerateHashValue(src.Key));
                })
                .ForMember(dest => dest.Timestamp, opt => opt.Ignore())
                .ForMember(dest => dest.ETag,
                           opt => {
                    opt.MapFrom(src => KeyGeneratorHelper.ETagWildCard);
                }).ConstructUsing((n) => new PersistedGrantTblEntity());
                cfg.CreateMap <PersistedGrantTblEntity, PersistedGrant>()
                .ConstructUsing((n) => new PersistedGrant());
            });

            KeyMapperConfiguration.CompileMappings();

            KeyMapper = KeyMapperConfiguration.CreateMapper();
            KeyMapper.ConfigurationProvider.AssertConfigurationIsValid();

            SubjectMapperConfiguration = new MapperConfiguration((cfg) =>
            {
                cfg.CreateMap <PersistedGrant, PersistedGrantTblEntity>()
                .ForMember(dest => dest.RowKey,
                           opt => {
                    opt.MapFrom(src => KeyGeneratorHelper.GenerateHashValue(src.Key));
                })
                .ForMember(dest => dest.PartitionKey,
                           opt => {
                    opt.MapFrom(src => KeyGeneratorHelper.GenerateHashValue(src.SubjectId));
                })
                .ForMember(dest => dest.Timestamp, opt => opt.Ignore())
                .ForMember(dest => dest.ETag,
                           opt => {
                    opt.MapFrom(src => KeyGeneratorHelper.ETagWildCard);
                }).ConstructUsing((n) => new PersistedGrantTblEntity());
                cfg.CreateMap <PersistedGrantTblEntity, PersistedGrant>()
                .ConstructUsing((n) => new PersistedGrant());
            });

            SubjectMapperConfiguration.CompileMappings();

            SubjectMapper = SubjectMapperConfiguration.CreateMapper();
            SubjectMapper.ConfigurationProvider.AssertConfigurationIsValid();
        }
Ejemplo n.º 9
0
        public async Task RemoveAllAsync(string subjectId, string clientId, string type)
        {
            CloudTable table = StorageContext.PersistedGrantTable;

            string hashedSubject = KeyGeneratorHelper.GenerateHashValue(subjectId);

            string partitionKeyFilter = TableQuery.GenerateFilterCondition("PartitionKey",
                                                                           QueryComparisons.Equal,
                                                                           hashedSubject);

            string rowClientFilter = TableQuery.GenerateFilterCondition("ClientId",
                                                                        QueryComparisons.Equal,
                                                                        clientId);

            string rowTypeFilter = TableQuery.GenerateFilterCondition("Type",
                                                                      QueryComparisons.Equal,
                                                                      type);

            string rowFilter = TableQuery.CombineFilters(rowClientFilter, TableOperators.And, rowTypeFilter);

            string filter = TableQuery.CombineFilters(partitionKeyFilter, TableOperators.And, rowFilter);

            TableQuery <PersistedGrantTblEntity> tq = new TableQuery <PersistedGrantTblEntity>();

            tq.FilterString = filter;

            _logger.LogDebug($"removing persisted grants from database for subject {subjectId}, clientId {clientId}, grantType {type}");

            var mainTasks = (await StorageContext.GetAllByTableQueryAsync(tq, StorageContext.PersistedGrantTable).ConfigureAwait(false))
                            .Select(subjectEntity =>
            {
                var deletes = subjectEntity.ToModel().ToEntities();
                return(Task.WhenAll(StorageContext.GetAndDeleteTableEntityByKeysAsync(deletes.keyGrant.PartitionKey, deletes.keyGrant.RowKey, StorageContext.PersistedGrantTable),
                                    table.ExecuteAsync(TableOperation.Delete(subjectEntity)),
                                    StorageContext.DeleteBlobAsync(subjectEntity.Key, StorageContext.PersistedGrantBlobContainer)));
            });

            try
            {
                await Task.WhenAll(mainTasks);
            }
            catch (AggregateException agg)
            {
                ExceptionHelper.LogStorageExceptions(agg, (tableEx) =>
                {
                    _logger.LogDebug($"error removing persisted grants from table storage for subject {subjectId}, clientId {clientId}");
                }, (blobEx) =>
                {
                    _logger.LogDebug($"error removing persisted grants from blob storage for subject {subjectId}, clientId {clientId}");
                });
            }
        }
Ejemplo n.º 10
0
        public void GenerateDateTimeDecendingId_Equal()
        {
            DateTime now = DateTime.UtcNow;

            Console.WriteLine(now.ToLongDateString() + " " + now.ToLongTimeString());
            string nowBlobName = KeyGeneratorHelper.GenerateDateTimeDecendingId(now);

            Console.WriteLine($"now blob: {nowBlobName}");

            DateTime old = now.AddMinutes(-1);

            Console.WriteLine(old.ToLongDateString() + " " + old.ToLongTimeString());
            string oldBlobName = KeyGeneratorHelper.GenerateDateTimeDecendingId(old);

            Console.WriteLine($"old blob: {oldBlobName}");

            DateTime newer = now.AddMinutes(5);

            Console.WriteLine(newer.ToLongDateString() + " " + newer.ToLongTimeString());
            string newBlobName = KeyGeneratorHelper.GenerateDateTimeDecendingId(newer);

            Console.WriteLine($"newer blob: {newBlobName}");


            int nowToOld = String.Compare(nowBlobName, oldBlobName);

            Console.WriteLine($"String.Compare(nowBlobName, oldBlobName): {nowToOld}");
            Assert.AreEqual <int>(-1, nowToOld);

            int oldToNow = String.Compare(oldBlobName, nowBlobName);

            Console.WriteLine($"String.Compare(oldBlobName, nowBlobName): {oldToNow}");
            Assert.AreEqual <int>(1, oldToNow);

            int nowToNewer = String.Compare(nowBlobName, newBlobName);

            Console.WriteLine($"String.Compare(nowBlobName, newBlobName): {nowToNewer}");
            Assert.AreEqual <int>(1, nowToNewer);

            int newerToNow = String.Compare(newBlobName, nowBlobName);

            Console.WriteLine($"String.Compare(newBlobName, nowBlobName): {newerToNow}");
            Assert.AreEqual <int>(-1, newerToNow);

            Assert.AreEqual <int>(0, String.Compare(nowBlobName, nowBlobName));
        }
Ejemplo n.º 11
0
        public async Task SaveBlobAsync(string keyNotHashed, string jsonEntityContent, CloudBlobContainer container)
        {
            CloudBlockBlob blob = container.GetBlockBlobReference(KeyGeneratorHelper.GenerateHashValue(keyNotHashed));

            blob.Properties.ContentType = "application/json";

            await blob.UploadTextAsync(jsonEntityContent,
                                       Encoding.UTF8,
                                       Microsoft.Azure.Storage.AccessCondition.GenerateEmptyCondition(),
                                       new BlobRequestOptions()
            {
            },
                                       new Microsoft.Azure.Storage.OperationContext()
            {
            },
                                       new System.Threading.CancellationToken());

            await blob.SetPropertiesAsync();
        }
        public async Task <IEnumerable <PersistedGrant> > GetAllAsync(string subjectId)
        {
            string hashedSubject = KeyGeneratorHelper.GenerateHashValue(subjectId);

            string partitionKeyFilter = TableQuery.GenerateFilterCondition("PartitionKey",
                                                                           QueryComparisons.Equal,
                                                                           hashedSubject);

            TableQuery <PersistedGrantTblEntity> tq = new TableQuery <PersistedGrantTblEntity>();

            tq.FilterString = partitionKeyFilter;

            var list = (await StorageContext.GetAllByTableQueryAsync(tq, StorageContext.PersistedGrantTable))
                       .Select(s => s.ToModel()).ToList();

            foreach (var m in list)
            {
                m.Data = await StorageContext.GetBlobContentAsync(m.Key, StorageContext.PersistedGrantBlobContainer);
            }
            _logger.LogDebug("{persistedGrantCount} persisted grants found for {subjectId}", list.Count, subjectId);
            return(list);
        }
        public async Task <string> GetBlobContentAsync(string keyNotHashed, BlobContainerClient container)
        {
            BlobClient blob = container.GetBlobClient(KeyGeneratorHelper.GenerateHashValue(keyNotHashed));

            return(await GetBlobContentAsync(blob).ConfigureAwait(false));
        }
Ejemplo n.º 14
0
 public async Task DeleteBlobAsync(string keyNotHashed, CloudBlobContainer container)
 {
     CloudBlockBlob blob = container.GetBlockBlobReference(KeyGeneratorHelper.GenerateHashValue(keyNotHashed));
     await blob.DeleteIfExistsAsync();
 }
Ejemplo n.º 15
0
        public async Task <Entity> GetEntityBlobAsync <Entity>(string keyNotHashed, CloudBlobContainer container) where Entity : class, new()
        {
            CloudBlockBlob blob = container.GetBlockBlobReference(KeyGeneratorHelper.GenerateHashValue(keyNotHashed));

            return(await GetEntityBlobAsync <Entity>(blob));
        }
Ejemplo n.º 16
0
        public async Task <string> GetBlobContentAsync(string keyNotHashed, CloudBlobContainer container)
        {
            CloudBlockBlob blob = container.GetBlockBlobReference(KeyGeneratorHelper.GenerateHashValue(keyNotHashed));

            return(await GetBlobContentAsync(blob));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Generates a unique key.
        /// </summary>
        ///
        /// <typeparam name="T">
        /// Key's type.
        /// </typeparam>
        ///
        /// <param name="keyGeneratorType">
        /// Type of the KeyGenerator to use.
        /// </param>
        ///
        /// <param name="parameters">
        /// Parameters to compute the unique key.
        /// </param>
        ///
        /// <returns>
        /// The unique key.
        /// </returns>
        public static T GenerateKey <T>(Type keyGeneratorType, object[] parameters = null)
        {
            IKeyGenerator <T> keyGenerator = KeyGeneratorHelper.CreateKeyGenerator <T>(keyGeneratorType);

            return(keyGenerator.Generate(parameters));
        }