public async Task StoreAuthorizationCodeAsync_should_update_entity() { using var store = new RavenDbTestDriverWrapper().GetDocumentStore(); var serializer = new PersistentGrantSerializer(); var loggerMock = new Mock <ILogger <AuthorizationCodeStore> >(); var authorizationCode = new AuthorizationCode { ClientId = "test", Subject = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(JwtClaimTypes.Subject, "test") })) }; using var s1 = store.OpenAsyncSession(); await s1.StoreAsync(new Entity.AuthorizationCode { Id = "test", ClientId = "test", UserId = "test", Data = serializer.Serialize(authorizationCode) }, $"{nameof(Entity.AuthorizationCode)}/test"); await s1.SaveChangesAsync(); using var session = store.OpenAsyncSession(); var sut = new AuthorizationCodeStore(new ScopedAsynDocumentcSession(session), serializer, loggerMock.Object); var code = await sut.StoreAuthorizationCodeAsync(authorizationCode); Assert.Equal("test", code); }
public async Task RemoveAsync() { //Arrange var sut = new AuthorizationCodeStore(NhibernateSession, ScopeStoreMock.Object, ClientStoreMock.Object); var testKey = Guid.NewGuid().ToString(); var testCode = ObjectCreator.GetAuthorizationCode(); var nhCode = new Token { Key = testKey, SubjectId = testCode.SubjectId, ClientId = testCode.ClientId, JsonCode = ConvertToJson(testCode), Expiry = DateTime.UtcNow.AddSeconds(testCode.Client.AuthorizationCodeLifetime), TokenType = TokenType.AuthorizationCode }; ExecuteInTransaction(session => { session.Save(nhCode); }); //Act await sut.RemoveAsync(testKey); //Assert ExecuteInTransaction(session => { var token = session.Query <Token>() .SingleOrDefault(t => t.TokenType == TokenType.AuthorizationCode && t.Key == testKey); Assert.Null(token); }); }
public async Task RemoveAuthorizationCodeAsync_should_delete_entity() { using var store = new RavenDbTestDriverWrapper().GetDocumentStore(); var serializer = new PersistentGrantSerializer(); var loggerMock = new Mock <ILogger <AuthorizationCodeStore> >(); using var s1 = store.OpenAsyncSession(); await s1.StoreAsync(new Entity.AuthorizationCode { Id = "test", ClientId = "test", Data = serializer.Serialize(new AuthorizationCode { ClientId = "test" }) }, $"{nameof(Entity.AuthorizationCode)}/test"); await s1.SaveChangesAsync(); using var session = store.OpenAsyncSession(); var sut = new AuthorizationCodeStore(new ScopedAsynDocumentcSession(session), serializer, loggerMock.Object); await sut.RemoveAuthorizationCodeAsync("test"); using var s2 = store.OpenAsyncSession(); var result = await s2.LoadAsync <Entity.AuthorizationCode>($"{nameof(Entity.AuthorizationCode)}/test"); Assert.Null(result); }
public void GetAsync_WhenCalled_ExpectResponse() { // Arrange var mockCacheManager = new Mock<ICacheManager<AuthorizationCode>>(); var mockCacheConfiguration = new Mock<IConfiguration<RedisCacheConfigurationEntity>>(); mockCacheConfiguration.Setup(r => r.Get).Returns(new RedisCacheConfigurationEntity { CacheDuration = 1 }); var keyCallback = default(string); mockCacheManager.Setup(r => r.GetAsync(It.IsAny<string>())) .Callback((string s) => keyCallback = s) .ReturnsAsync(new AuthorizationCode()); var authorizationCodeStore = new AuthorizationCodeStore( mockCacheManager.Object, mockCacheConfiguration.Object); // Act var stopwatch = Stopwatch.StartNew(); var authorizationCode = authorizationCodeStore.GetAsync("string").Result; stopwatch.Stop(); // Assert this.WriteTimeElapsed(stopwatch); Assert.That(authorizationCode, Is.Not.Null); Assert.That(keyCallback, Is.EqualTo("ACS_string")); }
public void Setup() { base.Setup(); _clientStore = new ClientStore(StoreSettings.UsingFolder(TargetFolder)); _scopeStore = new ScopeStore(StoreSettings.UsingFolder(TargetFolder)); _authorizationCodeHandleStore = new AuthorizationCodeStore(StoreSettings.UsingFolder(TargetFolder)); _tokenHandleStore = new TokenHandleStore(StoreSettings.UsingFolder(TargetFolder)); }
private static void CreateSut(out Mock <IAdminStore <AuthorizationCode> > storeMock, out AuthorizationCodeStore sut) { storeMock = new Mock <IAdminStore <AuthorizationCode> >(); var serializerMock = new Mock <IPersistentGrantSerializer>(); sut = new AuthorizationCodeStore(storeMock.Object, serializerMock.Object); }
static List <AuthorizationCodeHandleRecord> InsertTestData(ClientStore clientStore, ScopeStore scopeStore, AuthorizationCodeStore authorizationCodeStore, TokenHandleStore ths, int count = 1) { var tokenInsert = TokenHandleStoreTest.InsertTestData(clientStore, scopeStore, ths, 10); var clientId = tokenInsert[0].Record.ClientId; string subjectSeed = Guid.NewGuid().ToString(); List <AuthorizationCodeHandleRecord> result = new List <AuthorizationCodeHandleRecord>(); int i = 0; foreach (var tokenRecord in tokenInsert) { var client = clientStore.FindClientByIdAsync(tokenRecord.Record.ClientId); AuthorizationCodeHandle handle = new AuthorizationCodeHandle { ClientId = tokenRecord.Record.ClientId, SubjectId = tokenRecord.Record.SubjectId, Expires = DateTimeOffset.UtcNow.AddMinutes(5), CreationTime = DateTimeOffset.UtcNow, IsOpenId = true, RedirectUri = "REDIRECTURI/" + i, WasConsentShown = true, Nonce = "NONCE:" + i, ClaimIdentityRecords = new List <ClaimIdentityRecord>() { new ClaimIdentityRecord() { AuthenticationType = Constants.PrimaryAuthenticationType, ClaimTypeRecords = new List <ClaimTypeRecord>() { new ClaimTypeRecord() { Type = Constants.ClaimTypes.Subject, Value = tokenRecord.Record.SubjectId, ValueType = "VALUETYPE:" + i } } } }, RequestedScopes = client.Result.AllowedScopes, Key = Guid.NewGuid().ToString(), }; var handleRecord = new AuthorizationCodeHandleRecord(handle); authorizationCodeStore.CreateAsync(handleRecord.Record); result.Add(handleRecord); ++i; } return(result); }
public async Task TestGetAllAsync() { var insert = await CassandraTestHelper.InsertTestData_AuthorizationCode(10); var subjectId = insert[0].SubjectId; var clientId = insert[0].ClientId; IAuthorizationCodeStore authStore = new AuthorizationCodeStore(); var find_metadata = await authStore.GetAllAsync(subjectId); Assert.AreEqual(find_metadata.Count(), insert.Count); }
public void GetAsync_WhenCalled_ExpectResponse() { // Arrange var mockCacheConfiguration = new Mock<IConfiguration<RedisCacheConfigurationEntity>>(); mockCacheConfiguration.Setup(r => r.Get).Returns( new RedisCacheConfigurationEntity { CacheDuration = 10, RedisCacheDefaultPrefix = "DEFAULT", UseObjectCompression = false }); var jsonSettingsFactory = new JsonSettingsFactory(new CustomMappersConfiguration()); var cacheManager = new RedisCacheManager<AuthorizationCode>( RedisHelpers.ConnectionMultiplexer, mockCacheConfiguration.Object, jsonSettingsFactory.Create()); var authorizationCodeStore = new AuthorizationCodeStore( cacheManager, mockCacheConfiguration.Object); // Act var stopwatch = Stopwatch.StartNew(); var authorizationCode = authorizationCodeStore.GetAsync("Existing").Result; stopwatch.Stop(); // Assert this.WriteTimeElapsed(stopwatch); Assert.That(authorizationCode, Is.Not.Null); Assert.That(authorizationCode.Client, Is.Not.Null); Assert.That(authorizationCode.ClientId, Is.EqualTo("cid")); Assert.That(authorizationCode.CodeChallenge, Is.EqualTo("CodeChallenge")); Assert.That(authorizationCode.CodeChallengeMethod, Is.EqualTo("CodeChallengeMethod")); Assert.That(authorizationCode.CreationTime, Is.EqualTo(new DateTimeOffset(new DateTime(2016, 1, 1)))); Assert.That(authorizationCode.IsOpenId, Is.True); Assert.That(authorizationCode.Nonce, Is.EqualTo("Nonce")); Assert.That(authorizationCode.RedirectUri, Is.EqualTo("RedirectUri")); Assert.That(authorizationCode.RequestedScopes, Is.Not.Null); Assert.That(authorizationCode.RequestedScopes.Count(), Is.EqualTo(1)); Assert.That(authorizationCode.Scopes, Is.Not.Null); Assert.That(authorizationCode.Scopes.Count(), Is.EqualTo(1)); Assert.That(authorizationCode.SessionId, Is.EqualTo("SessionId")); Assert.That(authorizationCode.WasConsentShown, Is.True); Assert.That(authorizationCode.Subject, Is.Not.Null); }
public async Task StoreAuthorizationCodeAsync_should_throw_when_subject_is_null() { using var store = new RavenDbTestDriverWrapper().GetDocumentStore(); var serializer = new PersistentGrantSerializer(); var loggerMock = new Mock <ILogger <AuthorizationCodeStore> >(); using var session = store.OpenAsyncSession(); var sut = new AuthorizationCodeStore(new ScopedAsynDocumentcSession(session), serializer, loggerMock.Object); await Assert.ThrowsAsync <InvalidOperationException>(() => sut.StoreAuthorizationCodeAsync(new AuthorizationCode())); }
public async Task StoreAuthorizationCodeAsync_should_throw_when_subject_claim_is_not_found() { using var store = new RavenDbTestDriverWrapper().GetDocumentStore(); var serializer = new PersistentGrantSerializer(); var loggerMock = new Mock <ILogger <AuthorizationCodeStore> >(); using var session = store.OpenAsyncSession(); var sut = new AuthorizationCodeStore(new ScopedAsynDocumentcSession(session), serializer, loggerMock.Object); await Assert.ThrowsAsync <Exception>(() => sut.StoreAuthorizationCodeAsync(new AuthorizationCode { Subject = new ClaimsPrincipal(new ClaimsIdentity()) })); }
public async Task RemoveAuthorizationCodeAsync_should_not_throw_when_entity_not_exist() { using var store = new RavenDbTestDriverWrapper().GetDocumentStore(); var serializer = new PersistentGrantSerializer(); var loggerMock = new Mock <ILogger <AuthorizationCodeStore> >(); using var session = store.OpenAsyncSession(); var sut = new AuthorizationCodeStore(new ScopedAsynDocumentcSession(session), serializer, loggerMock.Object); await sut.RemoveAuthorizationCodeAsync("test"); using var s2 = store.OpenAsyncSession(); var result = await s2.LoadAsync <Entity.AuthorizationCode>($"{nameof(Entity.AuthorizationCode)}/test"); Assert.Null(result); }
public async Task TestRemoveAsync() { var insert = await CassandraTestHelper.InsertTestData_AuthorizationCode(1); var subjectId = insert[0].SubjectId; var clientId = insert[0].ClientId; var key = insert[0].Key; IAuthorizationCodeStore authStore = new AuthorizationCodeStore(); var find_metadata = await authStore.GetAsync(key); Assert.IsNotNull(find_metadata); await authStore.RemoveAsync(key); find_metadata = await authStore.GetAsync(key); Assert.IsNull(find_metadata); }
public void GetAllAsync_WhenCalled_ExpectThrows() { // Arrange var mockCacheManager = new Mock<ICacheManager<AuthorizationCode>>(); var mockCacheConfiguration = new Mock<IConfiguration<RedisCacheConfigurationEntity>>(); mockCacheConfiguration.Setup(r => r.Get).Returns(new RedisCacheConfigurationEntity { CacheDuration = 1 }); var authorizationCodeStore = new AuthorizationCodeStore( mockCacheManager.Object, mockCacheConfiguration.Object); // Act and Assert var stopwatch = Stopwatch.StartNew(); Assert.Throws<NotImplementedException>( () => authorizationCodeStore.GetAllAsync("string").GetAwaiter().GetResult()); stopwatch.Stop(); this.WriteTimeElapsed(stopwatch); }
public async Task StoreAuthorizationCodeAsync_should_create_entity() { using var store = new RavenDbTestDriverWrapper().GetDocumentStore(); var serializer = new PersistentGrantSerializer(); var loggerMock = new Mock <ILogger <AuthorizationCodeStore> >(); using var session = store.OpenAsyncSession(); var sut = new AuthorizationCodeStore(new ScopedAsynDocumentcSession(session), serializer, loggerMock.Object); var code = await sut.StoreAuthorizationCodeAsync(new AuthorizationCode { ClientId = "test", Subject = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(JwtClaimTypes.Subject, "test") })) }); using var s2 = store.OpenAsyncSession(); var result = await s2.LoadAsync <Entity.AuthorizationCode>($"{nameof(Entity.AuthorizationCode)}/{code}"); Assert.NotNull(result); }
public async Task GetAsync() { //Arrange var sut = new AuthorizationCodeStore(NhibernateSession, ScopeStoreMock.Object, ClientStoreMock.Object); var testKey = Guid.NewGuid().ToString(); var testCode = ObjectCreator.GetAuthorizationCode(); var nhCode = new Token { Key = testKey, SubjectId = testCode.SubjectId, ClientId = testCode.ClientId, JsonCode = ConvertToJson(testCode), Expiry = DateTime.UtcNow.AddSeconds(testCode.Client.AuthorizationCodeLifetime), TokenType = TokenType.AuthorizationCode }; SetupScopeStoreMock(); ExecuteInTransaction(session => { session.Save(nhCode); }); //Act var token = await sut.GetAsync(testKey); //Assert Assert.NotNull(token); //CleanUp ExecuteInTransaction(session => { session.Delete(nhCode); session.Clear(); }); }
public async Task StoreAsync() { //Arrange var sut = new AuthorizationCodeStore(NhibernateSession, ScopeStoreMock.Object, ClientStoreMock.Object); var testKey = Guid.NewGuid().ToString(); var testCode = ObjectCreator.GetAuthorizationCode(); //Act await sut.StoreAsync(testKey, testCode); ExecuteInTransaction(session => { //Assert var token = session.Query <Token>() .SingleOrDefault(t => t.TokenType == TokenType.AuthorizationCode && t.Key == testKey); Assert.NotNull(token); //CleanUp session.Delete(token); }); }
private static void CreateSut(out IServiceScope scope, out OperationalDbContext context, out AuthorizationCodeStore sut) { var provider = new ServiceCollection() .AddLogging() .AddOperationalEntityFrameworkStores(options => options.UseInMemoryDatabase(GenerateId())) .BuildServiceProvider(); scope = provider.CreateScope(); var serviceProvider = scope.ServiceProvider; context = serviceProvider.GetRequiredService <OperationalDbContext>(); sut = serviceProvider.GetRequiredService <AuthorizationCodeStore>(); }
public void RemoveAsync_WhenCalled_ExpectAction() { // Arrange var mockCacheManager = new Mock<ICacheManager<AuthorizationCode>>(); var mockCacheConfiguration = new Mock<IConfiguration<RedisCacheConfigurationEntity>>(); mockCacheConfiguration.Setup(r => r.Get).Returns(new RedisCacheConfigurationEntity { CacheDuration = 1 }); var keyCallback = default(string); mockCacheManager.Setup(r => r.DeleteAsync(It.IsAny<string>())) .Callback((string s) => keyCallback = s) .Returns(Task.FromResult(0)); var authorizationCodeStore = new AuthorizationCodeStore( mockCacheManager.Object, mockCacheConfiguration.Object); // Act var stopwatch = Stopwatch.StartNew(); authorizationCodeStore.RemoveAsync("string").Wait(); stopwatch.Stop(); // Assert this.WriteTimeElapsed(stopwatch); Assert.That(keyCallback, Is.EqualTo("ACS_string")); mockCacheManager.Verify(r => r.DeleteAsync(It.IsAny<string>()), Times.Once()); }
public void StoreAsync_WhenCalled_ExpectAction() { // Arrange var mockCacheConfiguration = new Mock<IConfiguration<RedisCacheConfigurationEntity>>(); mockCacheConfiguration.Setup(r => r.Get).Returns( new RedisCacheConfigurationEntity { CacheDuration = 10, RedisCacheDefaultPrefix = "DEFAULT", UseObjectCompression = false }); var jsonSettingsFactory = new JsonSettingsFactory(new CustomMappersConfiguration()); var cacheManager = new RedisCacheManager<AuthorizationCode>( RedisHelpers.ConnectionMultiplexer, mockCacheConfiguration.Object, jsonSettingsFactory.Create()); var authorizationCodeStore = new AuthorizationCodeStore( cacheManager, mockCacheConfiguration.Object); var subject = new ClaimsPrincipal( new List<ClaimsIdentity> { new ClaimsIdentity( new List<Claim> { new Claim(Constants.ClaimTypes.Subject, "sid") }) }); var code = new AuthorizationCode { Client = new Client { ClientId = "cid" }, RequestedScopes = new List<Scope> { new Scope { Description = "this is description", Enabled = true, Name = "Scope", DisplayName = "Display Name" } }, Subject = subject }; // Act var stopwatch = Stopwatch.StartNew(); authorizationCodeStore.StoreAsync("KeyToStore", code).Wait(); stopwatch.Stop(); // Assert this.WriteTimeElapsed(stopwatch); var redisValue = RedisHelpers.ConnectionMultiplexer.GetDatabase().StringGet("DEFAULT_ACS_KeyToStore"); Assert.That(redisValue.HasValue, Is.True); Console.WriteLine(redisValue); }
public void RemoveAsync_WhenCalled_ExpectAction() { // Arrange var mockCacheConfiguration = new Mock<IConfiguration<RedisCacheConfigurationEntity>>(); mockCacheConfiguration.Setup(r => r.Get).Returns( new RedisCacheConfigurationEntity { CacheDuration = 10, RedisCacheDefaultPrefix = "DEFAULT", UseObjectCompression = false }); var jsonSettingsFactory = new JsonSettingsFactory(new CustomMappersConfiguration()); var cacheManager = new RedisCacheManager<AuthorizationCode>( RedisHelpers.ConnectionMultiplexer, mockCacheConfiguration.Object, jsonSettingsFactory.Create()); var authorizationCodeStore = new AuthorizationCodeStore( cacheManager, mockCacheConfiguration.Object); // Act var stopwatch = Stopwatch.StartNew(); authorizationCodeStore.RemoveAsync("Delete").Wait(); stopwatch.Stop(); // Assert this.WriteTimeElapsed(stopwatch); var redisValue = RedisHelpers.ConnectionMultiplexer.GetDatabase().StringGet("DEFAULT_ACS_Delete"); Assert.That(redisValue.HasValue, Is.False); }
/// <summary> /// Initializes this instance. /// </summary> /// <returns>The <see cref="Caches"/></returns> private static Entities.Caches Initialize() { var jsonSettingsFactory = new JsonSettingsFactory(incomingMappers); var settings = jsonSettingsFactory.Create(); var authorizationCacheManager = new RedisCacheManager<AuthorizationCode>( ConnectionMultiplexer, Configuration, settings); var authorizationCodeStore = new AuthorizationCodeStore( authorizationCacheManager, Configuration); var clientCacheManager = new RedisCacheManager<Client>( ConnectionMultiplexer, Configuration, settings); var clientCache = new ClientStoreCache( clientCacheManager, Configuration); var refreshTokenCacheManager = new RedisCacheManager<RefreshToken>( ConnectionMultiplexer, Configuration, settings); var refreshTokenStore = new RefreshTokenStore( refreshTokenCacheManager, Configuration); var scopeCacheManager = new RedisCacheManager<IEnumerable<Scope>>( ConnectionMultiplexer, Configuration, settings); var scopesCache = new ScopeStoreCache( scopeCacheManager, Configuration); var redisHandleCacheManager = new RedisCacheManager<Token>( ConnectionMultiplexer, Configuration, settings); var tokenHandleStore = new TokenHandleStore( redisHandleCacheManager, Configuration); var userServiceCacheManager = new RedisCacheManager<IEnumerable<Claim>>( ConnectionMultiplexer, Configuration, settings); var userServiceCache = new UserServiceCache( userServiceCacheManager, Configuration); var caches = new Entities.Caches { AuthorizationCodeStore = authorizationCodeStore, ClientCache = clientCache, RefreshTokenStore = refreshTokenStore, ScopesCache = scopesCache, TokenHandleStore = tokenHandleStore, UserServiceCache = userServiceCache }; return caches; }
private static void CreateSut(out IServiceScope scope, out OperationalDbContext context, out AuthorizationCodeStore sut) { var provider = new ServiceCollection() .AddLogging() .Configure <MemoryCacheOptions>(options => { }) .Configure <IdentityServer4.Configuration.IdentityServerOptions>(options => { }) .AddTransient(p => p.GetRequiredService <IOptions <IdentityServer4.Configuration.IdentityServerOptions> >().Value) .AddScoped(typeof(IFlushableCache <>), typeof(FlushableCache <>)) .AddOperationalEntityFrameworkStores(options => options.UseInMemoryDatabase(GenerateId())) .BuildServiceProvider(); scope = provider.CreateScope(); var serviceProvider = scope.ServiceProvider; context = serviceProvider.GetRequiredService <OperationalDbContext>(); sut = serviceProvider.GetRequiredService <AuthorizationCodeStore>(); }
public async Task GetAllAsync() { //Arrange var sut = new AuthorizationCodeStore(NhibernateSession, ScopeStoreMock.Object, ClientStoreMock.Object); var subjectId1 = Guid.NewGuid().ToString(); var subjectId2 = Guid.NewGuid().ToString(); var testKey1 = Guid.NewGuid().ToString(); var testCode1 = ObjectCreator.GetAuthorizationCode(subjectId1); var nhCode1 = new Token { Key = testKey1, SubjectId = testCode1.SubjectId, ClientId = testCode1.ClientId, JsonCode = ConvertToJson(testCode1), Expiry = DateTime.UtcNow.AddSeconds(testCode1.Client.AuthorizationCodeLifetime), TokenType = TokenType.AuthorizationCode }; var testKey2 = Guid.NewGuid().ToString(); var testCode2 = ObjectCreator.GetAuthorizationCode(subjectId1); var nhCode2 = new Token { Key = testKey2, SubjectId = testCode2.SubjectId, ClientId = testCode2.ClientId, JsonCode = ConvertToJson(testCode2), Expiry = DateTime.UtcNow.AddSeconds(testCode2.Client.AuthorizationCodeLifetime), TokenType = TokenType.AuthorizationCode }; var testKey3 = Guid.NewGuid().ToString(); var testCode3 = ObjectCreator.GetAuthorizationCode(subjectId2); var nhCode3 = new Token { Key = testKey3, SubjectId = testCode3.SubjectId, ClientId = testCode3.ClientId, JsonCode = ConvertToJson(testCode3), Expiry = DateTime.UtcNow.AddSeconds(testCode3.Client.AuthorizationCodeLifetime), TokenType = TokenType.AuthorizationCode }; var testKey4 = Guid.NewGuid().ToString(); var testCode4 = ObjectCreator.GetAuthorizationCode(subjectId2); var nhCode4 = new Token { Key = testKey4, SubjectId = testCode4.SubjectId, ClientId = testCode4.ClientId, JsonCode = ConvertToJson(testCode4), Expiry = DateTime.UtcNow.AddSeconds(testCode4.Client.AuthorizationCodeLifetime), TokenType = TokenType.AuthorizationCode }; SetupScopeStoreMock(); ExecuteInTransaction(session => { session.Save(nhCode1); session.Save(nhCode2); session.Save(nhCode3); session.Save(nhCode4); }); //Act var tokens = (await sut.GetAllAsync(subjectId1)).ToList(); //Assert Assert.True(tokens.Count == 2); Assert.True(tokens.All(t => t.SubjectId == subjectId1)); //CleanUp ExecuteInTransaction(session => { session.Delete(nhCode1); session.Delete(nhCode2); session.Delete(nhCode3); session.Delete(nhCode4); }); }