public Task StoreAsync(PersistedGrant token)
        {
            try
            {
                var existing = _repository.AllAsync.SingleOrDefault(x => x.Key == token.Key);
                if (existing == null)
                {
                    _logger.LogDebug($"{token.Key} not found in database");

                    var persistedGrant = token.ToEntity();
                    _repository.AddAsync(persistedGrant);
                }
                else
                {
                    _logger.LogDebug($"{token.Key} found in database");

                    existing = token.ToEntity();
                    _repository.UpdateAsync(x => x.Key == token.Key, existing);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(0, ex, "Exception storing persisted grant");
            }

            return(Task.FromResult(0));
        }
예제 #2
0
        /// <summary>
        /// Stores the asynchronous.
        /// </summary>
        /// <param name="token">The token.</param>
        /// <returns></returns>
        public Task StoreAsync(PersistedGrant token)
        {
            var existing = PersistedGrants.FindByKey(token.Key);

            if (existing == null)
            {
                _logger.LogDebug("{persistedGrantKey} not found in database", token.Key);

                existing = token.ToEntity();
            }
            else
            {
                _logger.LogDebug("{persistedGrantKey} found in database", token.Key);

                token.UpdateEntity(existing);
            }

            try
            {
                existing.Save();
            }
            catch (Exception ex)
            {
                _logger.LogWarning("exception updating {persistedGrantKey} persisted grant in database: {error}", token.Key, ex.Message);
            }

            return(Task.FromResult(0));
        }
예제 #3
0
        public void map_PersistedGrant_to_Entity()
        {
            var persistedGrant = new PersistedGrant()
            {
                ClientId     = NewGuidS,
                CreationTime = DateTime.UtcNow,
                Data         = NewGuidS,
                Expiration   = DateTime.UtcNow.AddMinutes(60),
                Key          = NewGuidS,
                SubjectId    = NewGuidS,
                Type         = NewGuidS
            };
            var entity = persistedGrant.ToEntity();

            entity.Etag = NewGuidS;
            entity.TTL  = 20;

            var actual = entity.ToModel();

            persistedGrant.ClientId.Should().Be(actual.ClientId);
            persistedGrant.CreationTime.Should().Be(actual.CreationTime);
            persistedGrant.Data.Should().Be(actual.Data);
            persistedGrant.Expiration.Should().Be(actual.Expiration);
            persistedGrant.Key.Should().Be(actual.Key);
            persistedGrant.SubjectId.Should().Be(actual.SubjectId);
            persistedGrant.Type.Should().Be(actual.Type);
        }
        public async Task StoreAsync(PersistedGrant token)
        {
            using (var db = _contextFactory())
            {
                var existing = await db.PersistedGrants.SingleOrDefaultAsync(x => x.Key == token.Key);

                if (existing == null)
                {
                    //_logger.LogDebug("{persistedGrantKey} not found in database", token.Key);

                    var persistedGrant = token.ToEntity();
                    db.PersistedGrants.Add(persistedGrant);
                }
                else
                {
                    //_logger.LogDebug("{persistedGrantKey} found in database", token.Key);

                    token.UpdateEntity(existing);
                }

                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    //_logger.LogWarning("exception updating {persistedGrantKey} persisted grant in database: {error}", token.Key, ex.Message);
                }
            }
        }
        public Task StoreAsync(PersistedGrant token)
        {
            var existing = _context.PersistedGrants.SingleOrDefault(x => x.SiteId == _siteId && x.Key == token.Key);

            if (existing == null)
            {
                var persistedGrant = token.ToEntity();
                persistedGrant.SiteId = _siteId;
                _context.PersistedGrants.Add(persistedGrant);
            }
            else
            {
                token.UpdateEntity(existing);
            }

            try
            {
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                _logger.LogError(0, ex, "StoreAsync");
            }

            return(Task.FromResult(0));
        }
예제 #6
0
        public Task StoreAsync(PersistedGrant token)
        {
            var existing = _context.PersistedGrants.SingleOrDefault(x => x.Key == token.Key);

            if (existing == null)
            {
                _logger.LogDebug("{persistedGrantKey} not found in database", token.Key);

                var persistedGrant = token.ToEntity();
                _context.PersistedGrants.Add(persistedGrant);
            }
            else
            {
                _logger.LogDebug("{persistedGrantKey} found in database", token.Key);

                token.UpdateEntity(existing);
            }

            try
            {
                _context.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                _logger.LogWarning("exception updating {persistedGrantKey} persisted grant in database: {error}", token.Key, ex.Message);
            }

            return(Task.FromResult(0));
        }
예제 #7
0
        /// <inheritdoc/>
        public virtual async Task StoreAsync(PersistedGrant token)
        {
            var existing = await Context.PersistedGrants.AsQueryable().SingleOrDefaultAsync(x => x.Key == token.Key);

            if (existing == null)
            {
                Logger.LogDebug("{persistedGrantKey} not found in database", token.Key);

                var persistedGrant = token.ToEntity();
                Context.PersistedGrants.Add(persistedGrant);
            }
            else
            {
                Logger.LogDebug("{persistedGrantKey} found in database", token.Key);

                token.UpdateEntity(existing);
            }

            try
            {
                await Context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                Logger.LogWarning("exception updating {persistedGrantKey} persisted grant in database: {error}", token.Key, ex.Message);
            }
        }
예제 #8
0
        /// <inheritdoc/>
        public virtual async Task StoreAsync(PersistedGrant token)
        {
            var existing = await UnitOfWork.Query <XpoPersistedGrant>().SingleOrDefaultAsync(x => x.Key == token.Key);

            if (existing == null)
            {
                Logger.LogDebug("{persistedGrantKey} not found in database", token.Key);

                var persistedGrant = token.ToEntity(UnitOfWork);
                await UnitOfWork.SaveAsync(persistedGrant);
            }
            else
            {
                Logger.LogDebug("{persistedGrantKey} found in database", token.Key);

                token.UpdateEntity(existing);
                await UnitOfWork.SaveAsync(existing);
            }

            try
            {
                await UnitOfWork.CommitChangesAsync();
            }
            catch (LockingException ex)
            {
                Logger.LogWarning("exception updating {persistedGrantKey} persisted grant in database: {error}", token.Key, ex.Message);
            }
        }
예제 #9
0
        /// <inheritdoc />
        public virtual async Task StoreAsync(PersistedGrant token)
        {
            var existing = await Session.Query <Entities.PersistedGrant, PersistentGrantIndex>()
                           .SingleOrDefaultAsync(x => x.Key == token.Key);

            if (existing == null)
            {
                Logger.LogDebug("{persistedGrantKey} not found in database", token.Key);

                var persistedGrant = token.ToEntity();
                await Session.StoreAsync(persistedGrant);
            }
            else
            {
                Logger.LogDebug("{persistedGrantKey} found in database", token.Key);

                token.UpdateEntity(existing);
            }

            try
            {
                await Session.WaitForIndexAndSaveChangesAsync <PersistentGrantIndex>();
            }
            catch (Exception ex)
            {
                Logger.LogWarning("exception updating {persistedGrantKey} persisted grant in database: {error}", token.Key, ex.Message);
            }
        }
예제 #10
0
        public async Task StoreAsync(PersistedGrant token)
        {
            var site = _contextAccessor.HttpContext.GetTenant <SiteContext>();

            if (site == null)
            {
                _logger.LogError("sitecontext was null");
                return;
            }
            var _siteId = site.Id.ToString();

            var existing = await _context.PersistedGrants.SingleOrDefaultAsync(x => x.SiteId == _siteId && x.Key == token.Key)
                           .ConfigureAwait(false);

            if (existing == null)
            {
                var persistedGrant = token.ToEntity();
                persistedGrant.SiteId = _siteId;
                _context.PersistedGrants.Add(persistedGrant);
            }
            else
            {
                token.UpdateEntity(existing);
            }

            try
            {
                await _context.SaveChangesAsync().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger.LogError(0, ex, "StoreAsync");
            }
        }
        public async Task StoreAsync(PersistedGrant grant)
        {
            Guard.ForNull(grant, nameof(grant));
            Guard.ForNull(grant.CreationTime, nameof(grant.CreationTime));
            Guard.ForNull(grant.Expiration, nameof(grant.Expiration));
            Guard.ForNullOrWhitespace(grant.ClientId, nameof(grant.ClientId));
            Guard.ForNullOrWhitespace(grant.SubjectId, nameof(grant.SubjectId));
            Guard.ForNullOrWhitespace(grant.Data, nameof(grant.Data));
            Guard.ForNullOrWhitespace(grant.Key, nameof(grant.Key));
            Guard.ForNullOrWhitespace(grant.Type, nameof(grant.Type));

            if (grant.Expiration <= grant.CreationTime)
            {
                throw new ArgumentOutOfRangeException();
            }

            var entity = grant.ToEntity();
            var ttl    = (int)(entity.Expiration - entity.CreationTime)?.TotalSeconds;

            if (ttl <= 0)
            {
                ttl = -1;
            }
            entity.TTL = ttl;
            var response = await _persistedGrantCosmosStore.UpsertAsync(entity);

            if (!response.IsSuccess)
            {
                _logger.LogCritical("Could not store PersitedGrant");
            }
        }
        public void Add(PersistedGrant token)
        {
            var entity = token.ToEntity();

            using (var con = _options.DbProviderFactory.CreateConnection())
            {
                con.ConnectionString = _options.ConnectionString;
                con.Open();
                using (var t = con.BeginTransaction())
                {
                    try
                    {
                        var ret = con.Execute($"insert into PersistedGrants ({left}Key{right},ClientId,CreationTime,Data,Expiration,SubjectId,{left}Type{right}) values (@Key,@ClientId,@CreationTime,@Data,@Expiration,@SubjectId,@Type)", entity, commandTimeout: _options.CommandTimeOut, commandType: CommandType.Text, transaction: t);
                        if (ret != 1)
                        {
                            throw new Exception($"execute insert error,return values is {ret}");
                        }
                        t.Commit();
                    }
                    catch (Exception ex)
                    {
                        t.Rollback();
                        throw ex;
                    }
                }
            }
        }
        public Task StoreAsync(PersistedGrant token)
        {
            try
            {
                var existing = _context.PersistedGrants.SingleOrDefault(x => x.Key == token.Key);
                if (existing == null)
                {
                    _logger.LogDebug("{persistedGrantKey} not found in database", token.Key);

                    var persistedGrant = token.ToEntity();
                    _context.Add(persistedGrant);
                }
                else
                {
                    _logger.LogDebug("{persistedGrantKey} found in database", token.Key);

                    token.UpdateEntity(existing);
                    _context.Update(x => x.Key == token.Key, existing);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(0, ex, "Exception storing persisted grant");
            }

            return(Task.FromResult(0));
        }
        /// <inheritdoc />
        public virtual async Task StoreAsync(PersistedGrant token)
        {
            using (var session = OpenAsyncSession())
            {
                var hashedTokenKey = CryptographyHelper.CreateHash(token.Key);

                var existing = await session.Query <Entities.PersistedGrant, PersistedGrantIndex>()
                               .SingleOrDefaultAsync(x => x.Key == hashedTokenKey);

                if (existing == null)
                {
                    Logger.LogDebug("{persistedGrantKey} not found in database", token.Key);

                    var persistedGrant = token.ToEntity();
                    await session.StoreAsync(persistedGrant);

                    SetTokenExpirationInDocumentMetadata(session, persistedGrant);
                }
                else
                {
                    Logger.LogDebug("{persistedGrantKey} found in database", token.Key);

                    token.UpdateEntity(existing);
                }

                try
                {
                    await session.WaitForIndexAndSaveChangesAsync <PersistedGrantIndex>();
                }
                catch (Exception ex)
                {
                    Logger.LogWarning("exception updating {persistedGrantKey} persisted grant in database: {error}", token.Key, ex.Message);
                }
            }
        }
예제 #15
0
        public async Task StoreAsync(PersistedGrant token)
        {
            var site = _contextAccessor.HttpContext.GetTenant<SiteContext>();
            if (site == null)
            {
                _logger.LogError("sitecontext was null");
                return;
            }
            var _siteId = site.Id.ToString();

            var existing = await _context.PersistedGrants.SingleOrDefaultAsync(x => x.SiteId == _siteId && x.Key == token.Key)
                .ConfigureAwait(false);
            if (existing == null)
            {
                var persistedGrant = token.ToEntity();
                persistedGrant.SiteId = _siteId;
                _context.PersistedGrants.Add(persistedGrant);
            }
            else
            {
                token.UpdateEntity(existing);
            }

            try
            {
                await _context.SaveChangesAsync().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger.LogError(0, ex, "StoreAsync");
            }  
        }
예제 #16
0
        /// <summary>
        /// 新增授权信息
        /// </summary>
        /// <param name="token">The token.</param>
        /// <returns></returns>
        public virtual async Task StoreAsync(PersistedGrant token)
        {
            var existing = await Context.Query <Entities.PersistedGrant>().FirstOrDefaultAsync(x => x.Key == token.Key);

            if (existing == null)
            {
                Logger.LogDebug("{persistedGrantKey} not found in database", token.Key);

                var persistedGrant = token.ToEntity();
                await Context.Command <Entities.PersistedGrant>().AddAsync(persistedGrant);
            }
            else
            {
                Logger.LogDebug("{persistedGrantKey} found in database", token.Key);
                //更新实体传输
                token.UpdateEntity(existing);
                //执行命令
                await Context.Command <Entities.PersistedGrant>().UpdateAsync(x => x.Key == token.Key, new Dictionary <string, object>()
                {
                    { "Type", token.Type },
                    { "SubjectId", token.SubjectId },
                    { "ClientId", token.ClientId },
                    { "CreationTime", token.CreationTime },
                    { "Expiration", token.Expiration },
                    { "Data", token.Data }
                });
            }
        }
예제 #17
0
        public virtual async Task StoreAsync(PersistedGrant token)
        {
            var existing = await Session.Query <Entities.PersistedGrant>().SingleOrDefaultAsync(x => x.Key == token.Key);

            if (existing == null)
            {
                Logger.LogDebug("{persistedGrantKey} not found in database", token.Key);

                var persistedGrant = token.ToEntity();
                await Session.StoreAsync(persistedGrant);
            }
            else
            {
                Logger.LogDebug("{persistedGrantKey} found in database", token.Key);

                token.UpdateEntity(existing);
            }

            if (Options.SetTokenExpire && existing.Expiration.HasValue)
            {
                Session.Advanced.GetMetadataFor(existing)[Constants.Documents.Metadata.Expires] = existing.Expiration.Value.ToUniversalTime();
            }

            try
            {
                await Session.SaveChangesAsync();
            }
            catch (ConcurrencyException ex)
            {
                Logger.LogWarning("exception updating {persistedGrantKey} persisted grant in database: {error}", token.Key, ex.Message);
            }
        }
예제 #18
0
        /// <inheritdoc/>
        public virtual async Task StoreAsync(PersistedGrant token)
        {
            var existing = await FreeSql.Select <Entities.PersistedGrant>().Where(x => x.Key == token.Key).FirstAsync();

            try
            {
                if (existing == null)
                {
                    Logger.LogDebug("{persistedGrantKey} not found in database", token.Key);

                    var persistedGrant = token.ToEntity();
                    await FreeSql.Insert(persistedGrant).ExecuteAffrowsAsync();
                }
                else
                {
                    Logger.LogDebug("{persistedGrantKey} found in database", token.Key);

                    token.UpdateEntity(existing);
                    await FreeSql.Update <Entities.PersistedGrant>().SetSource(existing).ExecuteAffrowsAsync();
                }
            }
            catch (Exception ex)
            {
                Logger.LogWarning("exception updating {persistedGrantKey} persisted grant in database: {error}", token.Key, ex.Message);
            }
        }
예제 #19
0
        /// <inheritdoc/>
        public virtual async Task StoreAsync(PersistedGrant token)
        {
            var snapshot = await Context.PersistedGrants
                           .WhereEqualTo("Key", token.Key)
                           .Limit(1)
                           .GetSnapshotAsync()
                           .ConfigureAwait(false);

            DocumentReference docRef;

            Entities.PersistedGrant entity;

            if (snapshot.Count == 0)
            {
                Logger.LogDebug("{persistedGrantKey} not found in database", token.Key);
                docRef = Context.PersistedGrants.Document();
                entity = token.ToEntity();
            }
            else
            {
                Logger.LogDebug("{persistedGrantKey} found in database", token.Key);
                docRef = snapshot[0].Reference;
                entity = snapshot[0].ConvertTo <Entities.PersistedGrant>();
                token.UpdateEntity(entity);
            }

            await docRef.SetAsync(entity).ConfigureAwait(false);
        }
예제 #20
0
        /// <summary>
        /// Stores the grant.
        /// </summary>
        /// <param name="grant">The grant to store.</param>
        public async Task StoreAsync(PersistedGrant grant)
        {
            using (var tx = _session.BeginTransaction())
            {
                try
                {
                    var existingGrant = await _session.GetAsync <Entities.PersistedGrant>(grant.Key);

                    if (existingGrant == null)
                    {
                        _logger.LogDebug("{persistedGrantKey} not found in database. Creating it.", grant.Key);

                        await _session.SaveAsync(grant.ToEntity());
                    }
                    else
                    {
                        _logger.LogDebug("{persistedGrantKey} found in database. Updating it", grant.Key);

                        grant.UpdateEntity(existingGrant);
                        await _session.UpdateAsync(existingGrant);
                    }
                    await tx.CommitAsync();
                }
                catch (HibernateException ex)
                {
                    _logger.LogWarning("exception storing {persistedGrantKey} persisted grant in database: {error}",
                                       grant.Key, ex.Message);
                }
            }
        }
예제 #21
0
        public void CanMap()
        {
            var model        = new PersistedGrant();
            var mappedEntity = model.ToEntity();
            var mappedModel  = mappedEntity.ToModel();

            Assert.NotNull(mappedModel);
            Assert.NotNull(mappedEntity);
        }
        public void PersistedGrantAutomapperConfigurationIsValid()
        {
            var model        = new PersistedGrant();
            var mappedEntity = model.ToEntity();
            var mappedModel  = mappedEntity.ToModel();

            Assert.NotNull(mappedModel);
            Assert.NotNull(mappedEntity);
            PersistedGrantMappers.Mapper.ConfigurationProvider.AssertConfigurationIsValid();
        }
예제 #23
0
        public async Task StoreAsync(PersistedGrant token)
        {
            var persistedGrant = token.ToEntity();

            _logger.LogDebug("storing persisted grant: {persistedGrant}", persistedGrant);
            var table = await InitTable();

            var operation = TableOperation.InsertOrReplace(persistedGrant);
            var result    = await table.ExecuteAsync(operation);

            _logger.LogDebug("stored {persistedGrantKey} with result {result}", token.Key, result.HttpStatusCode);
        }
        public Task StoreAsync(PersistedGrant grant)
        {
            var existing = this.persistedGrantService.Get(grant.Key);

            if (existing == null)
            {
                var persistedGrant = grant.ToEntity();
                this.persistedGrantService.Add(persistedGrant);
            }
            else
            {
                this.persistedGrantService.Update(existing);
            }
            return(Task.FromResult(0));
        }
        public async Task StoreAsync(PersistedGrant token)
        {
            try
            {
                _logger.LogDebug("Try to save or update {persistedGrantKey} in database", token.Key);
                await _context.InsertOrUpdate(t => t.Key == token.Key, token.ToEntity());

                _logger.LogDebug("{persistedGrantKey} stored in database", token.Key);
            }
            catch (Exception ex)
            {
                _logger.LogError(0, ex, "Exception storing persisted grant");
                throw;
            }
        }
예제 #26
0
        public Task StoreAsync(PersistedGrant token)
        {
            var persistedGrant = token.ToEntity();

            _context.PersistedGrants.Add(persistedGrant);
            try
            {
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                _logger.LogError(0, ex, "StoreAsync");
            }

            return(Task.FromResult(0));
        }
예제 #27
0
        public void Update(PersistedGrant token)
        {
            var dbgrant = Get(token.Key);

            if (dbgrant == null)
            {
                throw new InvalidOperationException($"you can not update an notexisted PersistedGrant,key={token.Key}.");
            }
            var entity = token.ToEntity();

            using (var con = _options.DbProviderFactory.CreateConnection())
            {
                con.ConnectionString = _options.ConnectionString;
                con.Open();
                using (var t = con.BeginTransaction())
                {
                    try
                    {
                        var ret = con.Execute("update PersistedGrants" +
                                              "set ClientId = @ClientId," +
                                              "Data = @Data," +
                                              "Expiration = @Expiration," +
                                              "SubjectId = @SubjectId," +
                                              "Type = @Type," +
                                              "where Key = @Key", new
                        {
                            entity.Key,
                            entity.ClientId,
                            entity.Data,
                            entity.Expiration,
                            entity.SubjectId,
                            entity.Type
                        }, commandTimeout: _options.CommandTimeOut, commandType: CommandType.Text, transaction: t);
                        if (ret != 1)
                        {
                            throw new Exception($"execute insert error,return values is {ret}");
                        }
                        t.Commit();
                    }
                    catch (Exception ex)
                    {
                        t.Rollback();
                        throw ex;
                    }
                }
            }
        }
예제 #28
0
        public void CanMap()
        {
            var model = new PersistedGrant()
            {
                ConsumedTime = new System.DateTime(2020, 02, 03, 4, 5, 6)
            };

            var mappedEntity = model.ToEntity();

            mappedEntity.ConsumedTime.Value.Should().Be(new System.DateTime(2020, 02, 03, 4, 5, 6));

            var mappedModel = mappedEntity.ToModel();

            mappedModel.ConsumedTime.Value.Should().Be(new System.DateTime(2020, 02, 03, 4, 5, 6));

            Assert.NotNull(mappedModel);
            Assert.NotNull(mappedEntity);
        }
예제 #29
0
        public void Store(PersistedGrant grant)
        {
            var dbgrant = Get(grant.Key);

            if (dbgrant != null)
            {
                throw new InvalidOperationException($"you can not add an existed PersistedGrant,key={grant.Key}.");
            }
            var entity = grant.ToEntity();

            using (var con = _options.DbProviderFactory.CreateConnection())
            {
                con.ConnectionString = _options.ConnectionString;
                con.Open();
                using (var t = con.BeginTransaction())
                {
                    try
                    {
                        var ret = con.Execute("insert into PersistedGrants (Key,ClientId,CreationTime,Data,Expiration,SubjectId,Type) values (@Key,@ClientId,@CreationTime,@Data,@Expiration,@SubjectId,@Type,)", new
                        {
                            entity.Key,
                            entity.ClientId,
                            entity.CreationTime,
                            entity.Data,
                            entity.Expiration,
                            entity.SubjectId,
                            entity.Type
                        }, commandTimeout: _options.CommandTimeOut, commandType: CommandType.Text, transaction: t);
                        if (ret != 1)
                        {
                            throw new Exception($"execute insert error,return values is {ret}");
                        }
                        t.Commit();
                    }
                    catch (Exception ex)
                    {
                        t.Rollback();
                        throw ex;
                    }
                }
            }
        }
예제 #30
0
        public static void Tests() => Describe(nameof(PersistedGrantMappers), () =>
        {
            It("PersistedGrant Automapper Configuration is valid", () => PersistedGrantMappers.Mapper.ConfigurationProvider.AssertConfigurationIsValid <PersistedGrantMapperProfile>());

            It("Can map", () =>
            {
                using var session = new Session();
                var model         = new PersistedGrant()
                {
                    ConsumedTime = new System.DateTime(2020, 02, 03, 4, 5, 6)
                };

                var mappedEntity = model.ToEntity(session);
                mappedEntity.ConsumedTime.Value.Should().Be(new System.DateTime(2020, 02, 03, 4, 5, 6));

                var mappedModel = mappedEntity.ToModel();
                mappedModel.ConsumedTime.Value.Should().Be(new System.DateTime(2020, 02, 03, 4, 5, 6));

                mappedModel.Should().NotBeNull();
                mappedEntity.Should().NotBeNull();
            });
        });
예제 #31
0
        public async Task StoreAsync(PersistedGrant grant)
        {
            DocumentSnapshot persistedGrant =
                await GetPersistedGrant(nameof(PersistedGrant.Key), grant.Key).ConfigureAwait(false);

            if (persistedGrant.Exists)
            {
                _logger.LogDebug("{persistedGrantKey} found in database", grant.Key);

                Entities.PersistedGrant existing = persistedGrant.ConvertTo <Entities.PersistedGrant>();

                grant.UpdateEntity(existing);

                await persistedGrant.Reference.SetAsync(existing).ConfigureAwait(false);
            }
            else
            {
                _logger.LogDebug("{persistedGrant} not found in database", grant.Key);

                Entities.PersistedGrant persistedGrand = grant.ToEntity();
                await _context.PersistedGrants.AddAsync(persistedGrand).ConfigureAwait(false);
            }
        }