Ejemplo n.º 1
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");
            }
        }
Ejemplo n.º 2
0
    /// <inheritdoc/>
    public virtual async Task CreateSessionAsync(ServerSideSession session, CancellationToken cancellationToken = default)
    {
        cancellationToken = cancellationToken == CancellationToken.None ? CancellationTokenProvider.CancellationToken : cancellationToken;

        var entity = new Entities.ServerSideSession
        {
            Key         = session.Key,
            Scheme      = session.Scheme,
            SessionId   = session.SessionId,
            SubjectId   = session.SubjectId,
            DisplayName = session.DisplayName,
            Created     = session.Created,
            Renewed     = session.Renewed,
            Expires     = session.Expires,
            Data        = session.Ticket,
        };

        Context.ServerSideSessions.Add(entity);

        try
        {
            await Context.SaveChangesAsync(cancellationToken);

            Logger.LogDebug("Created new server-side session {serverSideSessionKey} in database", session.Key);
        }
        catch (DbUpdateConcurrencyException ex)
        {
            Logger.LogWarning("Exception creating new server-side session in database: {error}", ex.Message);
        }
    }
Ejemplo n.º 3
0
        /// <inheritdoc/>
        public virtual async Task StoreAsync(PersistedGrant token)
        {
            var existing = await Context.PersistedGrants.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);
            }
        }
Ejemplo n.º 4
0
        public async Task RemoveByDeviceCodeAsync(string deviceCode)
        {
            var site = _contextAccessor.HttpContext.GetTenant <SiteContext>();

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

            var deviceFlowCodes = await _context.DeviceFlowCodes
                                  .FirstOrDefaultAsync(x => x.DeviceCode == deviceCode && x.SiteId == siteId);

            if (deviceFlowCodes != null)
            {
                _logger.LogDebug("removing {deviceCode} device code from database", deviceCode);

                _context.DeviceFlowCodes.Remove(deviceFlowCodes);

                try
                {
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    _logger.LogInformation("exception removing {deviceCode} device code from database: {error}", deviceCode, ex.Message);
                }
            }
            else
            {
                _logger.LogDebug("no {deviceCode} device code found in database", deviceCode);
            }
        }
    /// <inheritdoc/>
    public virtual async Task StoreAsync(Duende.IdentityServer.Models.PersistedGrant token)
    {
        using var activity = Tracing.StoreActivitySource.StartActivity("PersistedGrantStore.Store");

        var existing = (await Context.PersistedGrants.Where(x => x.Key == token.Key)
                        .ToArrayAsync(CancellationTokenProvider.CancellationToken))
                       .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
        {
            await Context.SaveChangesAsync(CancellationTokenProvider.CancellationToken);
        }
        catch (DbUpdateConcurrencyException ex)
        {
            Logger.LogWarning("exception updating {persistedGrantKey} persisted grant in database: {error}", token.Key, ex.Message);
        }
    }
Ejemplo n.º 6
0
    /// <summary>
    /// Stores the device authorization request.
    /// </summary>
    /// <param name="deviceCode">The device code.</param>
    /// <param name="userCode">The user code.</param>
    /// <param name="data">The data.</param>
    /// <returns></returns>
    public virtual async Task StoreDeviceAuthorizationAsync(string deviceCode, string userCode, DeviceCode data)
    {
        using var activity = Tracing.StoreActivitySource.StartActivity("DeviceFlowStore.StoreDeviceAuthorization");

        Context.DeviceFlowCodes.Add(ToEntity(data, deviceCode, userCode));

        await Context.SaveChangesAsync(CancellationTokenProvider.CancellationToken);
    }
Ejemplo n.º 7
0
        private async Task SaveChangesAsync()
        {
            var count = 3;

            while (count > 0)
            {
                try
                {
                    await _persistedGrantDbContext.SaveChangesAsync();

                    return;
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    count--;

                    // we get this if/when someone else already deleted the records
                    // we want to essentially ignore this, and keep working
                    _logger.LogDebug("Concurrency exception removing expired grants: {exception}", ex.Message);

                    foreach (var entry in ex.Entries)
                    {
                        // mark this entry as not attached anymore so we don't try to re-delete
                        entry.State = EntityState.Detached;
                    }
                }
            }

            _logger.LogDebug("Too many concurrency exceptions. Exiting.");
        }
        /// <summary>
        /// Persists new key in store.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public Task StoreKeyAsync(SerializedKey key)
        {
            var entity = new Key
            {
                Id                = key.Id,
                Use               = Use,
                Created           = key.Created,
                Version           = key.Version,
                Algorithm         = key.Algorithm,
                Data              = key.Data,
                DataProtected     = key.DataProtected,
                IsX509Certificate = key.IsX509Certificate
            };

            Context.Keys.Add(entity);
            return(Context.SaveChangesAsync());
        }
Ejemplo n.º 9
0
    /// <summary>
    /// Persists new key in store.
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public Task StoreKeyAsync(SerializedKey key)
    {
        using var activity = Tracing.StoreActivitySource.StartActivity("SigningKeyStore.StoreKey");

        var entity = new Key
        {
            Id                = key.Id,
            Use               = Use,
            Created           = key.Created,
            Version           = key.Version,
            Algorithm         = key.Algorithm,
            Data              = key.Data,
            DataProtected     = key.DataProtected,
            IsX509Certificate = key.IsX509Certificate
        };

        Context.Keys.Add(entity);
        return(Context.SaveChangesAsync(CancellationTokenProvider.CancellationToken));
    }
Ejemplo n.º 10
0
        /// <summary>
        /// Removes the stale persisted grants.
        /// </summary>
        /// <returns></returns>
        protected virtual async Task RemoveGrantsAsync()
        {
            var found = Int32.MaxValue;

            while (found >= _options.TokenCleanupBatchSize)
            {
                var expiredGrants = await _persistedGrantDbContext.PersistedGrants
                                    .Where(x => x.Expiration < DateTime.UtcNow)
                                    .OrderBy(x => x.Key)
                                    .Take(_options.TokenCleanupBatchSize)
                                    .ToArrayAsync();

                found = expiredGrants.Length;
                _logger.LogInformation("Removing {grantCount} grants", found);

                if (found > 0)
                {
                    _persistedGrantDbContext.PersistedGrants.RemoveRange(expiredGrants);
                    try
                    {
                        await _persistedGrantDbContext.SaveChangesAsync();

                        if (_operationalStoreNotification != null)
                        {
                            await _operationalStoreNotification.PersistedGrantsRemovedAsync(expiredGrants);
                        }
                    }
                    catch (DbUpdateConcurrencyException ex)
                    {
                        // we get this if/when someone else already deleted the records
                        // we want to essentially ignore this, and keep working
                        _logger.LogDebug("Concurrency exception removing expired grants: {exception}", ex.Message);
                    }
                }
            }
        }
Ejemplo n.º 11
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (string.IsNullOrEmpty(DeviceFlowCode.UserCode))
            {
                return(Page());
            }

            var deviceFlowCode = await _context.DeviceFlowCodes.FindAsync(DeviceFlowCode.UserCode).ConfigureAwait(false);

            if (deviceFlowCode == null)
            {
                return(Page());
            }

            _context.DeviceFlowCodes.Remove(deviceFlowCode);
            await _context.SaveChangesAsync().ConfigureAwait(false);

            return(RedirectToPage("./Index"));
        }
Ejemplo n.º 12
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (string.IsNullOrEmpty(PersistedGrant.Key))
            {
                return(Page());
            }

            var persistedGrant = await _context.PersistedGrants.FindAsync(PersistedGrant.Key).ConfigureAwait(false);

            if (persistedGrant == null)
            {
                return(Page());
            }

            _context.PersistedGrants.Remove(persistedGrant);
            await _context.SaveChangesAsync().ConfigureAwait(false);

            return(RedirectToPage("./Index"));
        }
Ejemplo n.º 13
0
    /// <summary>
    /// Saves changes and handles concurrency exceptions.
    /// </summary>
    public static async Task <ICollection <T> > SaveChangesWithConcurrencyCheckAsync <T>(this IPersistedGrantDbContext context, ILogger logger, CancellationToken cancellationToken = default)
        where T : class
    {
        var list = new List <T>();

        var count = 3;

        while (count > 0)
        {
            try
            {
                await context.SaveChangesAsync(cancellationToken);

                return(list);
            }
            catch (DbUpdateConcurrencyException ex)
            {
                count--;

                // we get this if/when someone else already deleted the records
                // we want to essentially ignore this, and keep working
                logger.LogDebug("Concurrency exception removing records: {exception}", ex.Message);

                foreach (var entry in ex.Entries)
                {
                    // mark this entry as not attached anymore so we don't try to re-delete
                    entry.State = EntityState.Detached;
                    list.Add((T)entry.Entity);
                }
            }
        }

        logger.LogDebug("Too many concurrency exceptions. Exiting.");

        return(list);
    }
Ejemplo n.º 14
0
        /// <summary>
        /// Stores the device authorization request.
        /// </summary>
        /// <param name="deviceCode">The device code.</param>
        /// <param name="userCode">The user code.</param>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public virtual async Task StoreDeviceAuthorizationAsync(string deviceCode, string userCode, DeviceCode data)
        {
            Context.DeviceFlowCodes.Add(ToEntity(data, deviceCode, userCode));

            await Context.SaveChangesAsync();
        }