public async Task RemoveAllAsync(string subjectId, string clientId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(subjectId) ||
                    string.IsNullOrWhiteSpace(clientId))
                {
                    throw new ArgumentNullException(
                              "subject Id and/or client Id is empty or white space");
                }

                await _inner.RemoveAllAsync(subjectId, clientId);

                bool result = await _setFallBackPolicy
                              .ExecuteAsync(async() =>
                {
                    await Task.Run(() =>
                    {
                        _handle.cache.SearchService.RemoveByTags(
                            Utilities
                            .CreateCachePersistedGrantStoreTags(
                                subjectId,
                                clientId),
                            TagSearchOptions.ByAllTags);
                    }).ConfigureAwait(false);
                    return(true);
                }).ConfigureAwait(false);


                if (result)
                {
                    if (_debugLoggingEnabled)
                    {
                        _logger.LogDebug($"Persisted grants with subject id " +
                                         $"{subjectId} and client id {clientId} " +
                                         $"successfully removed");
                    }
                }
                else
                {
                    if (_errorLoggingEnabled)
                    {
                        _logger.LogDebug(
                            $"Caching problems with persistant store cache");
                    }
                }
            }
            catch (Exception ex)
            {
                if (_errorLoggingEnabled)
                {
                    _logger.LogError(
                        ex,
                        $"something went wrong with RemoveAllAsync " +
                        $"for {subjectId}, {clientId}");
                }
                throw;
            }
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> OnPostAsync(string logoutId = null, string returnUrl = null)
        {
            if (logoutId == null)
            {
                logoutId = await _interaction.CreateLogoutContextAsync();
            }

            LogoutRequest logoutContext = await _interaction.GetLogoutContextAsync(logoutId);

            AutomaticRedirectAfterSignOut = true;
            PostLogoutRedirectUri         = logoutContext?.PostLogoutRedirectUri;
            ClientName       = string.IsNullOrEmpty(logoutContext?.ClientName) ? logoutContext?.ClientId : logoutContext?.ClientName;
            SignOutIframeUrl = logoutContext?.SignOutIFrameUrl;

            // delete the local authentication cookie
            await _signInManager.SignOutAsync();

            try
            {
                // delete reference tokens
                var subjectId = HttpContext.User.Identity.GetSubjectId();
                await _persistedGrantStore.RemoveAllAsync(subjectId, "mvc_hybrid", "reference_token");

                await _persistedGrantStore.RemoveAllAsync(subjectId, "js", "reference_token");

                await _persistedGrantStore.RemoveAllAsync(subjectId, "react", "reference_token");

                // raise the logout event
                await _events.RaiseAsync(new UserLogoutSuccessEvent(User.GetSubjectId(), User.GetDisplayName()));

                _logger.LogInformation("User logged out.");

                // set this so UI rendering sees an anonymous user
                HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity());
            }
            catch (InvalidOperationException ioe)
            {
                if (ioe.Message == "sub claim is missing")
                {
                    _logger.LogWarning("Logged out user attempting to log out");
                }
                else
                {
                    throw;
                }
            }
            catch (Exception e)
            {
                _logger.LogError("Error while attempting to log user out.", e);
            }


            return(Page());
        }
Ejemplo n.º 3
0
    public async Task RemoveAllAsync_Should_RemoveAll_PeristedGrants_For_A_Given_Subject_And_ClientId()
    {
        //Arrange
        var persistedGrantsWithTestSubjectX = await _persistedGrantStore.GetAllAsync(new PersistedGrantFilter()
        {
            SubjectId = "TestSubject-X"
        });

        var persistedGrantsWithTestSubjectXBeforeLength = persistedGrantsWithTestSubjectX.ToArray().Length;

        //Act
        await _persistedGrantStore.RemoveAllAsync(new PersistedGrantFilter()
        {
            SubjectId = "TestSubject-X",
            ClientId  = "TestClientId-X"
        });

        //Assert
        persistedGrantsWithTestSubjectXBeforeLength.ShouldBe(2);

        var persistedGrants = (await _persistedGrantStore.GetAllAsync(new PersistedGrantFilter()
        {
            SubjectId = "TestClientId-37"
        })).ToArray();

        persistedGrants.ShouldNotBe(null);
        persistedGrants.Length.ShouldBe(0);
    }
Ejemplo n.º 4
0
        public async Task Store_Grants_And_Remove_them()
        {
            for (int i = 0; i < 5; i++)
            {
                var key = Guid.NewGuid().ToString("N");

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

                await persistedGrantStore.StoreAsync(grant);
            }

            await persistedGrantStore.RemoveAllAsync(new PersistedGrantFilter
            {
                SubjectId = "sub1"
            });

            var items = await persistedGrantStore.GetAllAsync(new PersistedGrantFilter
            {
                SubjectId = "sub1"
            });

            items.Should().BeEmpty();
        }
Ejemplo n.º 5
0
    /// <inheritdoc/>
    public virtual async Task ProcessLogoutAsync(UserSession session)
    {
        if (session.ClientIds.Count > 0)
        {
            var clientsToCoordinate = new List <string>();
            foreach (var clientId in session.ClientIds)
            {
                var client = await ClientStore.FindClientByIdAsync(clientId); // i don't think we care if it's an enabled client at this point

                if (client != null)
                {
                    var shouldCoordinate =
                        client.CoordinateLifetimeWithUserSession == true ||
                        (Options.Authentication.CoordinateClientLifetimesWithUserSession && client.CoordinateLifetimeWithUserSession != false);

                    if (shouldCoordinate)
                    {
                        clientsToCoordinate.Add(clientId);
                    }
                }
            }

            if (clientsToCoordinate.Count > 0)
            {
                Logger.LogDebug("Due to user logout, removing tokens for subject id {subjectId} and session id {sessionId}", session.SubjectId, session.SessionId);

                await PersistedGrantStore.RemoveAllAsync(new PersistedGrantFilter
                {
                    SubjectId = session.SubjectId,
                    SessionId = session.SessionId,
                    ClientIds = clientsToCoordinate,
                    Types     = PersistedGrantTokenTypes
                });
            }

            Logger.LogDebug("Due to user logout, invoking backchannel logout for subject id {subjectId} and session id {sessionId}", session.SubjectId, session.SessionId);

            // this uses all the clientIds since that's how logout worked before session coorindation existed
            // IOW, we know we're not using the clientsToCoordinate list here, also because it's active logout
            await BackChannelLogoutService.SendLogoutNotificationsAsync(new LogoutNotificationContext
            {
                SubjectId = session.SubjectId,
                SessionId = session.SessionId,
                ClientIds = session.ClientIds
            });
        }
    }
Ejemplo n.º 6
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 RemoveAllAsync_WhenSubIdAndClientIdOfExistingReceived_ExpectGrantDeleted()
        {
            // Arrange
            var persistedGrant = UniquePersistedGrant;

            // Act
            await _persistedGrantStore.StoreAsync(persistedGrant);

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

            Assert.IsNotNull(foundPersistedGrant);

            await _persistedGrantStore.RemoveAllAsync(persistedGrant.SubjectId, persistedGrant.ClientId);

            foundPersistedGrant = await _persistedGrantStore.GetAsync(persistedGrant.Key);


            // Assert
            Assert.IsNull(foundPersistedGrant);
        }
Ejemplo n.º 8
0
        /// <inheritdoc/>
        public Task RemoveAllGrantsAsync(string subjectId, string clientId = null, string sessionId = null)
        {
            if (String.IsNullOrWhiteSpace(subjectId))
            {
                throw new ArgumentNullException(nameof(subjectId));
            }

            return(_store.RemoveAllAsync(new PersistedGrantFilter {
                SubjectId = subjectId,
                ClientId = clientId,
                SessionId = sessionId
            }));
        }
    /// <inheritdoc/>
    public Task RemoveAllGrantsAsync(string subjectId, string clientId = null, string sessionId = null)
    {
        using var activity = Tracing.ServiceActivitySource.StartActivity("DefaultPersistedGrantService.RemoveAllGrants");

        if (String.IsNullOrWhiteSpace(subjectId))
        {
            throw new ArgumentNullException(nameof(subjectId));
        }

        return(_store.RemoveAllAsync(new PersistedGrantFilter {
            SubjectId = subjectId,
            ClientId = clientId,
            SessionId = sessionId
        }));
    }
Ejemplo n.º 10
0
        public async Task RevokeTokensAsync(string subjectId, string clientId)
        {
            await _persistedGrantStore.RemoveAllAsync(subjectId, clientId);

            var user = await _userManager.FindByIdAsync(subjectId);

            if (user == null)
            {
                throw new InvalidOperationException($"Could not find user with the specified id. User id: {subjectId}");
            }

            user.TokenRevokedDate = DateTimeOffset.UtcNow;

            await _userManager.UpdateAsync(user);
        }
Ejemplo n.º 11
0
    /// <inheritdoc/>
    public async Task RemoveSessionsAsync(RemoveSessionsContext context, CancellationToken cancellationToken = default)
    {
        if (context.RevokeTokens || context.RevokeConsents)
        {
            // delete the tokens
            var grantFilter = new PersistedGrantFilter
            {
                SubjectId = context.SubjectId,
                SessionId = context.SessionId,
            };

            if (context.ClientIds != null)
            {
                grantFilter.ClientIds = context.ClientIds;
            }

            if (!context.RevokeTokens || !context.RevokeConsents)
            {
                if (context.RevokeConsents)
                {
                    grantFilter.Type = IdentityServerConstants.PersistedGrantTypes.UserConsent;
                }
                else
                {
                    grantFilter.Types = OnlyTokenTypes;
                }
            }

            await _persistedGrantStore.RemoveAllAsync(grantFilter);
        }

        // send back channel SLO
        if (context.SendBackchannelLogoutNotification)
        {
            // we might have more than one, so load them all
            var sessions = await _serverSideTicketService.GetSessionsAsync(
                new SessionFilter
            {
                SubjectId = context.SubjectId,
                SessionId = context.SessionId,
            },
                cancellationToken);

            foreach (var session in sessions)
            {
                await _backChannelLogoutService.SendLogoutNotificationsAsync(new LogoutNotificationContext
                {
                    SubjectId = session.SubjectId,
                    SessionId = session.SessionId,
                    Issuer    = session.Issuer,
                    ClientIds = session.ClientIds.Where(x => context.ClientIds == null || context.ClientIds.Contains(x))
                });
            }
        }

        if (context.RemoveServerSideSession)
        {
            // delete the cookies
            await _serverSideSessionStore.DeleteSessionsAsync(new SessionFilter
            {
                SubjectId = context.SubjectId,
                SessionId = context.SessionId,
            }, cancellationToken);
        }
    }
 public Task RemoveAllAsync(PersistedGrantFilter filter)
 {
     return(_innerPersistedGrantStore.RemoveAllAsync(filter));
 }
Ejemplo n.º 13
0
 public async Task remove_all_subjectid_clientid()
 {
     _currentRemoveAllEntity = _currentManyEntities[0];
     await _persistedGrantStore.RemoveAllAsync(_currentRemoveAllEntity.SubjectId, _currentRemoveAllEntity.ClientId);
 }
 /// <summary>
 /// Removes all grants for a given subject id and client id combination.
 /// </summary>
 /// <param name="subjectId">The subject identifier.</param>
 /// <param name="clientId">The client identifier.</param>
 /// <returns></returns>
 public Task RemoveAllGrantsAsync(string subjectId, string clientId)
 {
     return(_store.RemoveAllAsync(subjectId, clientId));
 }
Ejemplo n.º 15
0
 public Task RemoveAllAsync(string subjectId, string clientId)
 {
     return(_inMemoryPersistedGrantStore.RemoveAllAsync(subjectId, clientId));
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Removes all items for a subject id / cliend id combination.
 /// </summary>
 /// <param name="subjectId">The subject identifier.</param>
 /// <param name="clientId">The client identifier.</param>
 /// <returns></returns>
 protected async Task RemoveAllAsync(string subjectId, string clientId)
 {
     await _store.RemoveAllAsync(subjectId, clientId, _grantType);
 }
Ejemplo n.º 17
0
 public Task RemoveReferenceTokensAsync(string subjectId, string clientId)
 {
     return(_store.RemoveAllAsync(subjectId, clientId, Constants.PersistedGrantTypes.ReferenceToken));
 }
 public Task RemoveAllAsync(string subjectId, string clientId)
 {
     return(_persistedGrantStoreImplementation.RemoveAllAsync(subjectId, clientId));
 }