public async Task CanCreateAndDeleteUser()
        {
            var user         = new MongoIdentityUser("test_account", "*****@*****.**");
            var createResult = await _userStore.CreateAsync(user, CancellationToken.None);

            createResult.ShouldNotBeNull();
            createResult.Succeeded.ShouldBeTrue();

            var deleteResult = await _userStore.DeleteAsync(user, CancellationToken.None);

            deleteResult.ShouldNotBeNull();
            deleteResult.Succeeded.ShouldBeTrue();
        }
        public async Task CanCreateUser()
        {
            var result = await userStore.CreateAsync(testUser, default(CancellationToken));

            Assert.Equal(IdentityResult.Success, result);
            var storedUser = (await usersCollection.FindAsync(u => u.Id == testUser.Id)).Single();

            Assert.NotNull(storedUser);
            Assert.True(testUser.PropertiesEqual(storedUser));
        }
Esempio n. 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <MongoDbSettings>(Configuration.GetSection("MongoDb"));
            services.AddSingleton <IUserStore <MongoIdentityUser> >(provider =>
            {
                var options  = provider.GetService <IOptions <MongoDbSettings> >();
                var client   = new MongoClient(options.Value.ConnectionString);
                var database = client.GetDatabase(options.Value.DatabaseName);

                return(MongoUserStore <MongoIdentityUser> .CreateAsync(database).GetAwaiter().GetResult());
            });

            services.AddIdentity <MongoIdentityUser>();

            services.AddMvc();

            services.AddIdentityServer(opts =>
            {
                //opts.PublicOrigin = "http://login.127.0.0.1.xip.io/";
                //opts.IssuerUri = "http://login.127.0.0.1.xip.io/";
            })
            .AddDeveloperSigningCredential()
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity <MongoIdentityUser>();
        }
Esempio n. 4
0
        public async Task SqlUserStoreMethodsThrowWhenDisposedTest()
        {
            var store = new MongoUserStore(Container.MongoRepository.Context);

            store.Dispose();
            await Assert.ThrowsAsync <ObjectDisposedException>(async() => await store.AddClaimsAsync(null, null));

            await Assert.ThrowsAsync <ObjectDisposedException>(async() => await store.AddLoginAsync(null, null));

            await Assert.ThrowsAsync <ObjectDisposedException>(async() => await store.AddToRoleAsync(null, null));

            await Assert.ThrowsAsync <ObjectDisposedException>(async() => await store.GetClaimsAsync(null));

            await Assert.ThrowsAsync <ObjectDisposedException>(async() => await store.GetLoginsAsync(null));

            await Assert.ThrowsAsync <ObjectDisposedException>(async() => await store.GetRolesAsync(null));

            await Assert.ThrowsAsync <ObjectDisposedException>(async() => await store.IsInRoleAsync(null, null));

            await Assert.ThrowsAsync <ObjectDisposedException>(async() => await store.RemoveClaimsAsync(null, null));

            await Assert.ThrowsAsync <ObjectDisposedException>(async() => await store.RemoveLoginAsync(null, null, null));

            await Assert.ThrowsAsync <ObjectDisposedException>(
                async() => await store.RemoveFromRoleAsync(null, null));

            await Assert.ThrowsAsync <ObjectDisposedException>(async() => await store.RemoveClaimsAsync(null, null));

            await Assert.ThrowsAsync <ObjectDisposedException>(async() => await store.ReplaceClaimAsync(null, null, null));

            await Assert.ThrowsAsync <ObjectDisposedException>(async() => await store.FindByLoginAsync(null, null));

            await Assert.ThrowsAsync <ObjectDisposedException>(async() => await store.FindByIdAsync(null));

            await Assert.ThrowsAsync <ObjectDisposedException>(async() => await store.FindByNameAsync(null));

            await Assert.ThrowsAsync <ObjectDisposedException>(async() => await store.CreateAsync(null));

            await Assert.ThrowsAsync <ObjectDisposedException>(async() => await store.UpdateAsync(null));

            await Assert.ThrowsAsync <ObjectDisposedException>(async() => await store.DeleteAsync(null));

            await Assert.ThrowsAsync <ObjectDisposedException>(
                async() => await store.SetEmailConfirmedAsync(null, true));

            await Assert.ThrowsAsync <ObjectDisposedException>(async() => await store.GetEmailConfirmedAsync(null));

            await Assert.ThrowsAsync <ObjectDisposedException>(
                async() => await store.SetPhoneNumberConfirmedAsync(null, true));

            await Assert.ThrowsAsync <ObjectDisposedException>(
                async() => await store.GetPhoneNumberConfirmedAsync(null));
        }
        public async Task MongoUserStore_ShouldPutThingsIntoUsersCollectionByDefault()
        {
            var user = new MongoIdentityUser(TestUtils.RandomString(10));


            using (var store = new MongoUserStore <MongoIdentityUser>(options))
            {
                // ACT
                var result = await store.CreateAsync(user, CancellationToken.None);

                // ASSERT
                Assert.True(result.Succeeded);

                Assert.Equal(1, await store.GetUserCountAsync());
            }
        }
        public async Task CreateAsync_ShouldCreateUser()
        {
            // ARRANGE
            MongoIdentityUser user;

            using (var userStore = new MongoUserStore <MongoIdentityUser>(options) as IUserStore <MongoIdentityUser>)
            {
                user = new MongoIdentityUser(TestUtils.RandomString(10));
                await userStore.CreateAsync(user, CancellationToken.None);

                var retrievedUser = await userStore.FindByIdAsync(user.Id, CancellationToken.None);

                Assert.NotNull(retrievedUser);
                Assert.Equal(user.UserName, retrievedUser.UserName);
                Assert.Equal(user.NormalizedUserName, retrievedUser.NormalizedUserName);
            }
        }
Esempio n. 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <MongoDbSettings>(Configuration.GetSection("MongoDb"));
            services.AddSingleton <IUserStore <MongoIdentityUser> >(provider =>
            {
                var options  = provider.GetService <IOptions <MongoDbSettings> >();
                var client   = new MongoClient(options.Value.ConnectionString);
                var database = client.GetDatabase(options.Value.DatabaseName);

                return(MongoUserStore <MongoIdentityUser> .CreateAsync(database).GetAwaiter().GetResult());
            });

            services.AddIdentity <MongoIdentityUser>()
            .AddDefaultTokenProviders();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Esempio n. 8
0
        public async Task MongoUserStore_ShouldPutThingsIntoUsersCollectionByDefault()
        {
            var user = new MongoIdentityUser(TestUtils.RandomString(10));

            using (var dbProvider = MongoDbServerTestUtils.CreateDatabase())
            {
                var store = await MongoUserStore <MongoIdentityUser> .CreateAsync(dbProvider.Database);

                // ACT
                var result = await store.CreateAsync(user, CancellationToken.None);

                // ASSERT
                Assert.True(result.Succeeded);
                var collections      = await(await dbProvider.Database.ListCollectionsAsync()).ToListAsync();
                var collectionExists = collections.Any(x => x["name"].ToString().Equals("users", StringComparison.Ordinal));
                Assert.True(collectionExists, "Default collection name should not be changed from the initial collection name ('users') since it will cause breaking change to current users");
            }
        }
Esempio n. 9
0
        public async Task MongoIdentityUser_CanBeSavedAndRetrieved_WhenItBecomesTheSubclass()
        {
            var username      = TestUtils.RandomString(10);
            var countryName   = TestUtils.RandomString(10);
            var loginProvider = TestUtils.RandomString(5);
            var providerKey   = TestUtils.RandomString(5);
            var displayName   = TestUtils.RandomString(5);
            var myCustomThing = TestUtils.RandomString(10);
            var user          = new MyIdentityUser(username)
            {
                MyCustomThing = myCustomThing
            };

            user.AddClaim(new Claim(ClaimTypes.Country, countryName));
            user.AddLogin(new MongoUserLogin(new UserLoginInfo(loginProvider, providerKey, displayName)));

            using (var dbProvider = MongoDbServerTestUtils.CreateDatabase())
            {
                var store = new MongoUserStore <MyIdentityUser>(dbProvider.Database);

                // ACT, ASSERT
                var result = await store.CreateAsync(user, CancellationToken.None);

                Assert.True(result.Succeeded);

                // ACT, ASSERT
                var retrievedUser = await store.FindByIdAsync(user.Id, CancellationToken.None);

                Assert.NotNull(retrievedUser);
                Assert.Equal(username, retrievedUser.UserName);
                Assert.Equal(myCustomThing, retrievedUser.MyCustomThing);

                var countryClaim = retrievedUser.Claims.FirstOrDefault(x => x.ClaimType == ClaimTypes.Country);
                Assert.NotNull(countryClaim);
                Assert.Equal(countryName, countryClaim.ClaimValue);

                var retrievedLoginProvider = retrievedUser.Logins.FirstOrDefault(x => x.LoginProvider == loginProvider);
                Assert.NotNull(retrievedLoginProvider);
                Assert.Equal(providerKey, retrievedLoginProvider.ProviderKey);
                Assert.Equal(displayName, retrievedLoginProvider.ProviderDisplayName);
            }
        }
        public async Task CreateAsync_ShouldCreateUser()
        {
            // ARRANGE
            using (var dbProvider = MongoDbServerTestUtils.CreateDatabase())
            {
                var userStore = new MongoUserStore <MongoIdentityUser>(dbProvider.Database) as IUserStore <MongoIdentityUser>;
                var user      = new MongoIdentityUser(TestUtils.RandomString(10));

                // ACT
                await userStore.CreateAsync(user, CancellationToken.None);

                // ASSERT
                var collection    = dbProvider.Database.GetDefaultCollection();
                var retrievedUser = await collection.FindByIdAsync(user.Id);

                Assert.NotNull(retrievedUser);
                Assert.Equal(user.UserName, retrievedUser.UserName);
                Assert.Equal(user.NormalizedUserName, retrievedUser.NormalizedUserName);
            }
        }
Esempio n. 11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <MongoDbSettings>(Configuration.GetSection("MongoDb"));
            services.AddSingleton <IUserStore <MongoIdentityUser> >(provider =>
            {
                var options  = provider.GetService <IOptions <MongoDbSettings> >();
                var client   = new MongoClient(options.Value.ConnectionString);
                var database = client.GetDatabase(options.Value.DatabaseName);

                return(MongoUserStore <MongoIdentityUser> .CreateAsync(database).GetAwaiter().GetResult());
            });

            services.AddIdentity <MongoIdentityUser>()
            .AddDefaultTokenProviders();

            services.AddMvc();

            // Add application services.
            services.AddTransient <IEmailSender, AuthMessageSender>();
            services.AddTransient <ISmsSender, AuthMessageSender>();
        }
Esempio n. 12
0
        public async Task MongoIdentityUser_ShouldSaveAndRetrieveTheFutureOccuranceCorrectly()
        {
            var lockoutEndDate = new DateTime(2017, 2, 1, 0, 0, 0, DateTimeKind.Utc).AddTicks(8996910);
            var user           = new MongoIdentityUser(TestUtils.RandomString(10));

            user.LockUntil(lockoutEndDate);

            using (var dbProvider = MongoDbServerTestUtils.CreateDatabase())
            {
                var store = await MongoUserStore <MongoIdentityUser> .CreateAsync(dbProvider.Database);

                // ACT
                var result = await store.CreateAsync(user, CancellationToken.None);

                // ASSERT
                Assert.True(result.Succeeded);
                var collection    = dbProvider.Database.GetCollection <MongoIdentityUser>(Constants.DefaultCollectionName);
                var retrievedUser = await collection.FindByIdAsync(user.Id);

                Assert.Equal(user.LockoutEndDate, retrievedUser.LockoutEndDate);
            }
        }
        public async Task MongoIdentityUser_ShouldSaveAndRetrieveTheFutureOccuranceCorrectly()
        {
            var lockoutEndDate = new DateTime(2017, 2, 1, 0, 0, 0, DateTimeKind.Utc).AddTicks(8996910);
            var user           = new MyIdentityUser(TestUtils.RandomString(10));

            user.LockUntil(lockoutEndDate);



            using (var store = new MongoUserStore <MyIdentityUser>(options))
            {
                // ACT
                var result = await store.CreateAsync(user, CancellationToken.None);

                // ASSERT
                Assert.True(result.Succeeded);

                var retrievedUser = await store.FindByIdAsync(user.Id, CancellationToken.None);

                Assert.Equal(user.LockoutEndDate, retrievedUser.LockoutEndDate);
            }
        }
Esempio n. 14
0
        public async Task UserStorePublicNullCheckTest()
        {
            Assert.Throws <ArgumentNullException>("context", () => new MongoUserStore(null));
            var store = new MongoUserStore(Container.MongoRepository.Context);
            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetUserIdAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetUserNameAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.SetUserNameAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.CreateAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.UpdateAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.DeleteAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.AddClaimsAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.ReplaceClaimAsync(null, null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.RemoveClaimsAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetClaimsAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetLoginsAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetRolesAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.AddLoginAsync(null, null));

            await
            Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.RemoveLoginAsync(null, null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.AddToRoleAsync(null, null));

            await
            Assert.ThrowsAsync <ArgumentNullException>("user",
                                                       async() => await store.RemoveFromRoleAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.IsInRoleAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetPasswordHashAsync(null));

            await
            Assert.ThrowsAsync <ArgumentNullException>("user",
                                                       async() => await store.SetPasswordHashAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetSecurityStampAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user",
                                                             async() => await store.SetSecurityStampAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("login", async() => await store.AddLoginAsync(new MongoDbIdentityUser("fake"), null));

            await Assert.ThrowsAsync <ArgumentNullException>("claims",
                                                             async() => await store.AddClaimsAsync(new MongoDbIdentityUser("fake"), null));

            await Assert.ThrowsAsync <ArgumentNullException>("claims",
                                                             async() => await store.RemoveClaimsAsync(new MongoDbIdentityUser("fake"), null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetEmailConfirmedAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user",
                                                             async() => await store.SetEmailConfirmedAsync(null, true));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetEmailAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.SetEmailAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetPhoneNumberAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.SetPhoneNumberAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user",
                                                             async() => await store.GetPhoneNumberConfirmedAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user",
                                                             async() => await store.SetPhoneNumberConfirmedAsync(null, true));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetTwoFactorEnabledAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user",
                                                             async() => await store.SetTwoFactorEnabledAsync(null, true));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetAccessFailedCountAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetLockoutEnabledAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.SetLockoutEnabledAsync(null, false));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetLockoutEndDateAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.SetLockoutEndDateAsync(null, new DateTimeOffset()));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.ResetAccessFailedCountAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.IncrementAccessFailedCountAsync(null));

            await Assert.ThrowsAsync <ArgumentException>("normalizedRoleName", async() => await store.AddToRoleAsync(new MongoDbIdentityUser("fake"), null));

            await Assert.ThrowsAsync <ArgumentException>("normalizedRoleName", async() => await store.RemoveFromRoleAsync(new MongoDbIdentityUser("fake"), null));

            await Assert.ThrowsAsync <ArgumentException>("normalizedRoleName", async() => await store.IsInRoleAsync(new MongoDbIdentityUser("fake"), null));

            await Assert.ThrowsAsync <ArgumentException>("normalizedRoleName", async() => await store.AddToRoleAsync(new MongoDbIdentityUser("fake"), ""));

            await Assert.ThrowsAsync <ArgumentException>("normalizedRoleName", async() => await store.RemoveFromRoleAsync(new MongoDbIdentityUser("fake"), ""));

            await Assert.ThrowsAsync <ArgumentException>("normalizedRoleName", async() => await store.IsInRoleAsync(new MongoDbIdentityUser("fake"), ""));
        }
        public static void AddIdentityTokenProvider(this IServiceCollection services)
        {
            IConfiguration conf = services.BuildServiceProvider().GetService <IConfiguration>();

            services.AddSingleton <IUserStore <MongoIdentityUser> >(provider =>
            {
                MongoClient client      = new MongoClient(conf.GetConnectionString("MongoServer"));
                IMongoDatabase database = client.GetDatabase("Seisicite");

                return(MongoUserStore <MongoIdentityUser> .CreateAsync(database).GetAwaiter().GetResult());
            });

            services.AddIdentity <MongoIdentityUser>()
            .AddDefaultTokenProviders();

            services.AddScoped <IdentityErrorDescriber, PersonalIdentityErrorDescriber>();

            services.Configure <IdentityOptions>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 6;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Lockout.MaxFailedAccessAttempts = 10;
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromHours(2);
            });

            IConfigurationSection secSettings = conf.GetSection("SecuritySettings");

            services.Configure <SecuritySettings>(secSettings);

            SecuritySettings secObj = secSettings.Get <SecuritySettings>();

            byte[] key = Encoding.ASCII.GetBytes(secObj.Secret);

            services.AddSingleton(secObj);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = true;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = true,
                    ValidateAudience         = false,
                    ValidIssuer = secObj.Issuer
                };
            });

            services.AddScoped <IRequestHandler <RegisterUserCommand, Token>, AuthCommandHandler>();
            services.AddScoped <IRequestHandler <RegisterUserEvaluatorCommand, Token>, AuthCommandHandler>();
            services.AddScoped <IRequestHandler <LoginCommand, Token>, AuthCommandHandler>();
            services.AddScoped <IRequestHandler <ResetPasswordCommand, bool>, AuthCommandHandler>();
        }