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); }
public async Task GetAllAsync_Should_Get_All_PersistedGrants_For_A_Given_SubjectId() { //Act var persistentGrants = await _persistedGrantStore.GetAllAsync("TestSubject").ConfigureAwait(false); //Assert var persistedGrants = persistentGrants as PersistedGrant[] ?? persistentGrants.ToArray(); persistedGrants.ShouldNotBe(null); persistedGrants.Length.ShouldBe(2); persistedGrants[0].SubjectId.ShouldBe("TestSubject"); persistedGrants[1].SubjectId.ShouldBe("TestSubject"); }
public async Task Store_Grants_And_Retrieve_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); } var items = await persistedGrantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1" }); items.Should().HaveCount(5); items = await persistedGrantStore.GetAllAsync(new PersistedGrantFilter { ClientId = "client1" }); items.Should().HaveCount(1); items = await persistedGrantStore.GetAllAsync(new PersistedGrantFilter { SessionId = "session1" }); items.Should().HaveCount(5); items = await persistedGrantStore.GetAllAsync(new PersistedGrantFilter { Type = "test" }); items.Should().HaveCount(5); }
public async Task remove_sessions_should_delete_refresh_tokens() { await _pipeline.LoginAsync("alice"); var authzResponse = await _pipeline.RequestAuthorizationEndpointAsync("client", "code", "openid api offline_access", "https://client/callback"); var tokenResponse = await _pipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest { Address = IdentityServerPipeline.TokenEndpoint, ClientId = "client", Code = authzResponse.Code, RedirectUri = "https://client/callback" }); (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).Should().NotBeEmpty(); await _sessionMgmt.RemoveSessionsAsync(new RemoveSessionsContext { SubjectId = "alice", RemoveServerSideSession = false, RevokeConsents = false, RevokeTokens = true, SendBackchannelLogoutNotification = false }); (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).Should().BeEmpty(); }
/// <summary> /// Fulls the log out. /// </summary> /// <returns> </returns> private async Task FullLogOut() { var subjectId = User.Identity.GetSubjectId(); var sessionId = await _userSession.GetSessionIdAsync().ConfigureAwait(false); var grants = await _persistedGrantStore.GetAllAsync(subjectId).ConfigureAwait(false); foreach (var persistedGrant in grants.Where(e => e.Data.Contains($"\"{sessionId}\""))) { await _persistedGrantStore.RemoveAsync(persistedGrant.Key).ConfigureAwait(false); } var keys = Request.Cookies.Keys; foreach (var key in keys) { Response.Cookies.Delete(key); } await _signInManager.SignOutAsync().ConfigureAwait(false); await HttpContext.SignOutAsync().ConfigureAwait(false); await _interaction.RevokeTokensForCurrentSessionAsync().ConfigureAwait(false); await _events.RaiseAsync(new UserLogoutSuccessEvent(User.GetSubjectId(), User.GetDisplayName())) .ConfigureAwait(false); }
public async Task get_subjects_Success() { var subjectId = _currentManyEntities[0].SubjectId; var entities = await _persistedGrantStore.GetAllAsync(subjectId); entities.Count().Should().Be(10); }
/// <summary> /// Gets all grants for a given subject ID. /// </summary> /// <param name="subjectId">The subject identifier.</param> /// <returns></returns> public async Task <IEnumerable <Consent> > GetAllGrantsAsync(string subjectId) { var grants = (await _store.GetAllAsync(subjectId)).ToArray(); try { var consents = grants.Where(x => x.Type == Constants.PersistedGrantTypes.UserConsent) .Select(x => _serializer.Deserialize <Consent>(x.Data)); var codes = grants.Where(x => x.Type == Constants.PersistedGrantTypes.AuthorizationCode) .Select(x => _serializer.Deserialize <AuthorizationCode>(x.Data)) .Select(x => new Consent { ClientId = x.ClientId, SubjectId = subjectId, Scopes = x.RequestedScopes, CreationTime = x.CreationTime, Expiration = x.CreationTime.AddSeconds(x.Lifetime) }); var refresh = grants.Where(x => x.Type == Constants.PersistedGrantTypes.RefreshToken) .Select(x => _serializer.Deserialize <RefreshToken>(x.Data)) .Select(x => new Consent { ClientId = x.ClientId, SubjectId = subjectId, Scopes = x.Scopes, CreationTime = x.CreationTime, Expiration = x.CreationTime.AddSeconds(x.Lifetime) }); var access = grants.Where(x => x.Type == Constants.PersistedGrantTypes.ReferenceToken) .Select(x => _serializer.Deserialize <Token>(x.Data)) .Select(x => new Consent { ClientId = x.ClientId, SubjectId = subjectId, Scopes = x.Scopes, CreationTime = x.CreationTime, Expiration = x.CreationTime.AddSeconds(x.Lifetime) }); consents = Join(consents, codes); consents = Join(consents, refresh); consents = Join(consents, access); return(consents.ToArray()); } catch (Exception ex) { _logger.LogError("Failed processing results from grant store. Exception: {0}", ex.Message); } return(Enumerable.Empty <Consent>()); }
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); }
/// <summary> Did user consent already asynchronous. </summary> /// <param name="returnUrl"> URL of the return. </param> /// <param name="context"> The context. </param> /// <returns> A Task<bool> </returns> public async Task <bool> DidUserConsentAlreadyAsync(string returnUrl, HttpContext context) { var user = context.User; var request = await _interaction.GetAuthorizationContextAsync(returnUrl); if (request == null) { return(false); } var client = await _clientStore.FindEnabledClientByIdAsync(request.ClientId); if (client == null) { return(false); } var grants = await _grantStore.GetAllAsync(user.Claims.First(c => c.Type == "sub").Value); var grantedAlready = grants.SingleOrDefault(g => g.Type == "user_consent" && g.ClientId == client.ClientId && (!g.Expiration.HasValue || g.Expiration >= DateTime.UtcNow)); if (grantedAlready == null) { return(false); } dynamic data = JsonConvert.DeserializeObject(grantedAlready.Data); var jScopes = data.Scopes; var scopes = new List <string>(); foreach (var jScope in jScopes) { scopes.Add(jScope.ToString()); } var grantedConsent = new ConsentResponse { RememberConsent = true, ScopesConsented = scopes }; // delete the grant key to let IdSrv readd it await _grantStore.RemoveAsync(grantedAlready.Key); // signal allowed grant, savin persisted grant await _interaction.GrantConsentAsync(request, grantedConsent); return(true); }
public async Task <IEnumerable <Consent> > GetAllGrantsAsync(string subjectId) { var grants = await _store.GetAllAsync(subjectId); var consents = grants.Where(x => x.Type == Constants.PersistedGrantTypes.UserConsent) .Select(x => _serializer.Deserialize <Consent>(x.Data)); var codes = grants.Where(x => x.Type == Constants.PersistedGrantTypes.AuthorizationCode) .Select(x => _serializer.Deserialize <AuthorizationCode>(x.Data)) .Select(x => new Consent { ClientId = x.ClientId, SubjectId = subjectId, Scopes = x.RequestedScopes, CreationTime = x.CreationTime, Expiration = x.CreationTime.AddSeconds(x.Lifetime) }); var refresh = grants.Where(x => x.Type == Constants.PersistedGrantTypes.RefreshToken) .Select(x => _serializer.Deserialize <RefreshToken>(x.Data)) .Select(x => new Consent { ClientId = x.ClientId, SubjectId = subjectId, Scopes = x.Scopes, CreationTime = x.CreationTime, Expiration = x.CreationTime.AddSeconds(x.Lifetime) }); var access = grants.Where(x => x.Type == Constants.PersistedGrantTypes.ReferenceToken) .Select(x => _serializer.Deserialize <Token>(x.Data)) .Select(x => new Consent { ClientId = x.ClientId, SubjectId = subjectId, Scopes = x.Scopes, CreationTime = x.CreationTime, Expiration = x.CreationTime.AddSeconds(x.Lifetime) }); consents = Join(consents, codes); consents = Join(consents, refresh); consents = Join(consents, access); return(consents.ToArray()); }
public async Task GetAsync_WithSubAndTypeAndPersistedGrantExists_ExpectPersistedGrantReturned() { // Arrange var persistedGrant = UniquePersistedGrant; // Act await _persistedGrantStore.StoreAsync(persistedGrant); // Assert var foundPersistedGrants = await _persistedGrantStore.GetAllAsync(persistedGrant.SubjectId); // Assert Assert.IsNotNull(foundPersistedGrants); Assert.IsTrue(foundPersistedGrants.Any()); }
public async Task Something(string sub) { var persistedGrants = await _store.GetAllAsync(sub); }
public async Task <IEnumerable <Models.PersistedGrant> > GetAllAsync( string subjectId) { try { if (string.IsNullOrWhiteSpace(subjectId)) { throw new ArgumentNullException( "Subject id cant be null or white space", nameof(subjectId)); } var dictionary = await _getPersistedGrantDictionaryPolicy .ExecuteAsync(async() => { return(await Task.Run(() => new Dictionary <string, PersistedGrant>( _handle.cache.SearchService.GetByTag <PersistedGrant>( Utilities .CreateCachedPersistedGrantStoreSubjectIdTag( subjectId))) ).ConfigureAwait(false)); }).ConfigureAwait(false); List <Models.PersistedGrant> persistedGrants = new List <Models.PersistedGrant>(); if (dictionary == null || dictionary.Count == 0) { persistedGrants = (await _inner.GetAllAsync(subjectId)).ToList(); string key; CacheItem item; Dictionary <string, CacheItem> cachePersistedGrants = new Dictionary <string, CacheItem>(persistedGrants.Count()); foreach (var persistedGrant in persistedGrants) { key = Utilities .CreateCachedPersistedGrantStoreKey( persistedGrant); item = new CacheItem(persistedGrant.ToEntity()) { Tags = Utilities .CreateCachePersistedGrantStoreTags( persistedGrant), Expiration = Utilities .DetermineCachePersistedGrantStoreExpiration( persistedGrant, _handle.options) }; cachePersistedGrants.Add(key, item); } if (cachePersistedGrants.Count() > 0) { if (_debugLoggingEnabled) { _logger.LogDebug( $"Cache Miss: All persisted grants with subject Id" + $" {subjectId} gotten from IPersistedGrantStore" + $" instance"); } var result = await _setFallBackPolicy .ExecuteAsync(async() => { await Task.Run(() => _handle.cache.InsertBulk(cachePersistedGrants)) .ConfigureAwait(false); return(true); }).ConfigureAwait(false); if (!result) { if (_errorLoggingEnabled) { _logger.LogError( $"Caching problems with persistant store cache"); } } } else { if (_debugLoggingEnabled) { _logger.LogDebug( $"No persisted grants found for subject id " + $"{subjectId}"); } } } else { persistedGrants .AddRange(dictionary .Values .ToList() .Select(x => x.ToModel())); if (_debugLoggingEnabled) { _logger.LogDebug( $"Cache Hit: All persisted grants with " + $"subject Id {subjectId} gotten from Cache"); } } return(persistedGrants); } catch (Exception ex) { if (_errorLoggingEnabled) { _logger.LogError( ex, $"something went wrong with GetAllAsync " + $"for {subjectId}"); } throw; } }
public Task <IEnumerable <PersistedGrant> > GetAllAsync(string subjectId) { return(_inMemoryPersistedGrantStore.GetAllAsync(subjectId)); }
/// <inheritdoc/> public async Task <IEnumerable <Grant> > GetAllGrantsAsync(string subjectId) { if (String.IsNullOrWhiteSpace(subjectId)) { throw new ArgumentNullException(nameof(subjectId)); } var grants = (await _store.GetAllAsync(new PersistedGrantFilter { SubjectId = subjectId })).ToArray(); try { var consents = grants.Where(x => x.Type == IdentityServerConstants.PersistedGrantTypes.UserConsent) .Select(x => _serializer.Deserialize <Consent>(x.Data)) .Select(x => new Grant { ClientId = x.ClientId, SubjectId = subjectId, Scopes = x.Scopes, CreationTime = x.CreationTime, Expiration = x.Expiration }); var codes = grants.Where(x => x.Type == IdentityServerConstants.PersistedGrantTypes.AuthorizationCode) .Select(x => _serializer.Deserialize <AuthorizationCode>(x.Data)) .Select(x => new Grant { ClientId = x.ClientId, SubjectId = subjectId, Description = x.Description, Scopes = x.RequestedScopes, CreationTime = x.CreationTime, Expiration = x.CreationTime.AddSeconds(x.Lifetime) }); var refresh = grants.Where(x => x.Type == IdentityServerConstants.PersistedGrantTypes.RefreshToken) .Select(x => _serializer.Deserialize <RefreshToken>(x.Data)) .Select(x => new Grant { ClientId = x.ClientId, SubjectId = subjectId, Description = x.Description, Scopes = x.Scopes, CreationTime = x.CreationTime, Expiration = x.CreationTime.AddSeconds(x.Lifetime) }); var access = grants.Where(x => x.Type == IdentityServerConstants.PersistedGrantTypes.ReferenceToken) .Select(x => _serializer.Deserialize <Token>(x.Data)) .Select(x => new Grant { ClientId = x.ClientId, SubjectId = subjectId, Description = x.Description, Scopes = x.Scopes, CreationTime = x.CreationTime, Expiration = x.CreationTime.AddSeconds(x.Lifetime) }); consents = Join(consents, codes); consents = Join(consents, refresh); consents = Join(consents, access); return(consents.ToArray()); } catch (Exception ex) { _logger.LogError(ex, "Failed processing results from grant store."); } return(Enumerable.Empty <Grant>()); }
public Task <IEnumerable <PersistedGrant> > GetAllAsync(string subjectId) { return(_persistedGrantStoreImplementation.GetAllAsync(subjectId)); }
private async Task <IEnumerable <UserConsentInfo> > GetPersistedGrantsAsync(string subjectId, string clientId, string consentType) { if (string.IsNullOrWhiteSpace(subjectId)) { throw new ArgumentNullException(nameof(subjectId)); } var grants = (await _persistedGrantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = subjectId, ClientId = clientId, Type = consentType })) .ToArray(); try { var consents = grants .Where(x => x.Type == PersistedGrantTypes.UserConsent) .Select(x => _serializer.Deserialize <Consent>(x.Data)) .Select(x => new UserConsentInfo { ClientId = x.ClientId, Scopes = x.Scopes, CreatedAt = x.CreationTime, ExpiresAt = x.Expiration, Type = PersistedGrantTypes.UserConsent }); var codes = grants .Where(x => x.Type == PersistedGrantTypes.AuthorizationCode) .Select(x => _serializer.Deserialize <AuthorizationCode>(x.Data)) .Select(x => new UserConsentInfo { ClientId = x.ClientId, Scopes = x.RequestedScopes, CreatedAt = x.CreationTime, ExpiresAt = x.CreationTime.AddSeconds(x.Lifetime), Type = PersistedGrantTypes.AuthorizationCode }); var refresh = grants .Where(x => x.Type == PersistedGrantTypes.RefreshToken) .Select(x => _serializer.Deserialize <RefreshToken>(x.Data)) .Select(x => new UserConsentInfo { ClientId = x.ClientId, Scopes = x.Scopes, Claims = x.AccessToken?.Claims?.Select(x => new BasicClaimInfo { Type = x.Type, Value = x.Value }), CreatedAt = x.CreationTime, ExpiresAt = x.CreationTime.AddSeconds(x.Lifetime), Type = PersistedGrantTypes.RefreshToken }); var access = grants .Where(x => x.Type == PersistedGrantTypes.ReferenceToken) .Select(x => _serializer.Deserialize <Token>(x.Data)) .Select(x => new UserConsentInfo { ClientId = x.ClientId, Scopes = x.Scopes, Claims = x.Claims.Select(x => new BasicClaimInfo { Type = x.Type, Value = x.Value }), CreatedAt = x.CreationTime, ExpiresAt = x.CreationTime.AddSeconds(x.Lifetime), Type = PersistedGrantTypes.ReferenceToken }); consents = Join(consents, codes); consents = Join(consents, refresh); consents = Join(consents, access); return(consents.ToArray()); } catch (Exception) { } return(Enumerable.Empty <UserConsentInfo>()); }
public Task <IEnumerable <PersistedGrant> > GetAllAsync(PersistedGrantFilter filter) { return(_innerPersistedGrantStore.GetAllAsync(filter)); }