/// <summary>
        /// Initializes a new instance of the <see cref="AuthenticationFlowTest"/> class.
        /// </summary>
        /// <param name="outputHelper">The test output helper.</param>
        public AuthenticationFlowTest(ITestOutputHelper outputHelper)
        {
            this.outputHelper             = outputHelper;
            this.testDatabase             = new TestDatabase(outputHelper);
            this.dbContext                = this.testDatabase.CreateContext();
            this.identityInstance         = IdentityTestHelper.CreateInstance(this.testDatabase, this.outputHelper);
            this.usedHttpContext          = new DefaultHttpContext();
            this.httpConctextAccessorMock = new Mock <IHttpContextAccessor>();
            this.jwtCrypoMock             = new Mock <IJwtCryptoProvider>();
            this.momentMock               = MomentTestHelper.CreateMomentMock();
            this.optionsMonitorMock       = OptionsTestHelper.CreateBackendOptionsMock();
            this.randomGenerator          = new SecureRandomGenerator();
            this.loggerFactory            = LoggingTestHelper.CreateLoggerFactory(this.outputHelper);

            this.httpConctextAccessorMock.SetupGet(m => m.HttpContext).Returns(this.usedHttpContext);

            this.jwtCrypoMock.SetupGet(c => c.Algorithm).Returns(SigningAlgorithm);
            this.jwtCrypoMock.SetupGet(c => c.SecurityKey).Returns(SigningKey);

            this.authenticationFlow = new AuthenticationFlow(
                this.httpConctextAccessorMock.Object,
                this.jwtCrypoMock.Object,
                this.identityInstance.UserManager,
                this.dbContext,
                this.randomGenerator,
                this.momentMock.Object,
                this.optionsMonitorMock.Object,
                this.loggerFactory.CreateLogger <AuthenticationFlow>());
        }
Exemple #2
0
        public async Task InvalidateRefreshTokensHappyFlow()
        {
            var rnd         = new Random();
            var tokenValues = Enumerable.Range(0, 3).Select(v =>
            {
                var arr = new byte[8];
                rnd.NextBytes(arr);
                return(arr);
            })
                              .ToImmutableList();

            var momentMock = MomentTestHelper.CreateMomentMock();

            using var testDb           = new TestDatabase(this.outputHelper);
            using var identityInstance = IdentityTestHelper.CreateInstance(testDb, this.outputHelper);
            using var testDbContext    = await testDb.CreateContextAsync().ConfigureAwait(true);

            var manager = new AuthManager(
                identityInstance.UserManager,
                testDbContext,
                momentMock.Object);

            var user = await identityInstance.CreateUserAsync("someone").ConfigureAwait(true);

            var user2 = await identityInstance.CreateUserAsync("someone1").ConfigureAwait(true);

            var claimsPrincipal = IdentityTestHelper.CreateClaimsPrincipalForUserId(user.Id);

            testDbContext.UserRefreshTokens.AddRange(tokenValues.Select((t, i) => new UserRefreshToken
            {
                TokenValue          = t,
                IpAddress           = "1.2.3",
                UserAgent           = "chrome",
                IsInvalidated       = false,
                SubjectUserId       = i < 2 ? user.Id : user2.Id,
                GeneratedAtUtc      = momentMock.Object.UtcNow,
                ExpiresAtUtc        = momentMock.Object.UtcNow.AddDays(1),
                ClientApplicationId = identityInstance.ClientId,
            }));
            await testDbContext.SaveChangesAsync().ConfigureAwait(true);

            await manager.InvalidateRefreshTokensAsync(
                claimsPrincipal).ConfigureAwait(true);

            (await testDbContext
             .UserRefreshTokens
             .Where(x => x.SubjectUserId == user.Id)
             .Select(x => x.IsInvalidated)
             .AllAsync(x => x).ConfigureAwait(true))
            .Should()
            .BeTrue(because: "the tokens should have been invalidated");

            (await testDbContext
             .UserRefreshTokens
             .Where(x => x.SubjectUserId == user2.Id)
             .Select(x => x.IsInvalidated)
             .AllAsync(x => !x).ConfigureAwait(true))
            .Should()
            .BeTrue(because: "the tokens should not have been invalidated");
        }
Exemple #3
0
        public async Task CreateUserAsyncHappyFlow()
        {
            var momentMock = MomentTestHelper.CreateMomentMock();

            using var testDb           = new TestDatabase(this.outputHelper);
            using var identityInstance = IdentityTestHelper.CreateInstance(testDb, this.outputHelper);
            using var testDbContext    = await testDb.CreateContextAsync().ConfigureAwait(true);

            var manager = new AuthManager(
                identityInstance.UserManager,
                testDbContext,
                momentMock.Object);

            var userName = "******";
            var password = "******";

            var result = await manager.CreateUserAsync(userName, password).ConfigureAwait(true);

            result.Should().BeNull(because: "no errors should have occurred");

            var user = await identityInstance.UserManager.FindByNameAsync(userName).ConfigureAwait(true);

            user.UserName.Should().Be(userName, because: "this was the user name of the created user");

            var userEntity = await testDbContext.Users.FindAsync(user.Id).ConfigureAwait(true);

            userEntity.Should().NotBeNull(because: "the user should have been inserted into the database");
        }
Exemple #4
0
        public async Task InvalidateRefreshTokenDoesNotBelongToUser()
        {
            var tokenValue    = new byte[] { 0x01, 0x02, 0x03, 0x04 };
            var tokenValueStr = Convert.ToBase64String(tokenValue);

            var momentMock = MomentTestHelper.CreateMomentMock();

            using var testDb           = new TestDatabase(this.outputHelper);
            using var identityInstance = IdentityTestHelper.CreateInstance(testDb, this.outputHelper);
            using var testDbContext    = await testDb.CreateContextAsync().ConfigureAwait(true);

            var manager = new AuthManager(
                identityInstance.UserManager,
                testDbContext,
                momentMock.Object);

            var user = await identityInstance.CreateUserAsync("someone").ConfigureAwait(true);

            var user2 = await identityInstance.CreateUserAsync("someone1").ConfigureAwait(true);

            var claimsPrincipal = IdentityTestHelper.CreateClaimsPrincipalForUserId(user.Id);

            var tokenEntity = new UserRefreshToken
            {
                TokenValue          = tokenValue,
                IpAddress           = "1.2.3",
                UserAgent           = "chrome",
                IsInvalidated       = false,
                SubjectUserId       = user2.Id,
                GeneratedAtUtc      = momentMock.Object.UtcNow,
                ExpiresAtUtc        = momentMock.Object.UtcNow.AddDays(1),
                ClientApplicationId = identityInstance.ClientId,
            };

            testDbContext.UserRefreshTokens.Add(tokenEntity);
            await testDbContext.SaveChangesAsync().ConfigureAwait(true);

            var result = await manager.InvalidateRefreshTokenAsync(
                claimsPrincipal,
                tokenValueStr).ConfigureAwait(true);

            result.Should().BeFalse(because: "the token should not have been found and invalidated");

            tokenEntity = await testDbContext.UserRefreshTokens
                          .FindAsync(tokenValue)
                          .ConfigureAwait(true);

            tokenEntity.IsInvalidated.Should().BeFalse(
                because: "the token was not invalidated");
        }
Exemple #5
0
        public async Task CreateUserEmptyPassword()
        {
            var momentMock = MomentTestHelper.CreateMomentMock();

            using var testDb           = new TestDatabase(this.outputHelper);
            using var identityInstance = IdentityTestHelper.CreateInstance(testDb, this.outputHelper);
            using var testDbContext    = await testDb.CreateContextAsync().ConfigureAwait(true);

            var manager = new AuthManager(
                identityInstance.UserManager,
                testDbContext,
                momentMock.Object);

            var userName = "******";
            var password = string.Empty;

            var result = await manager.CreateUserAsync(userName, password).ConfigureAwait(true);

            result.Should().NotBeEmpty(because: "an error should have occured");

            var user = await identityInstance.UserManager.FindByNameAsync(userName).ConfigureAwait(true);

            user.Should().BeNull(because: "the user should have never been created");
        }