Ejemplo n.º 1
0
        public static async Task SeedAsync(IServiceProvider serviceProvider)
        {
            var context = serviceProvider.GetService <IdentityDbContext>();

            string[] roles = new string[] { "Administrator", "User" };

            var roleStore = new RoleStore <IdentityRole>(context);

            foreach (var role in roles)
            {
                if (!context.Roles.Any(r => r.Name == role))
                {
                    var identityRole = new IdentityRole(role)
                    {
                        NormalizedName = role.ToLower()
                    };
                    await roleStore.CreateAsync(identityRole);

                    await roleStore.AddClaimAsync(identityRole, new Claim(CustomClaimsTypes.Permission, "view"));

                    await roleStore.AddClaimAsync(identityRole, new Claim(CustomClaimsTypes.Permission, "create"));

                    await roleStore.AddClaimAsync(identityRole, new Claim(CustomClaimsTypes.Permission, "update"));
                }
            }

            var adminUser = new User
            {
                FirstName            = "Администратор",
                Email                = "*****@*****.**",
                NormalizedEmail      = "*****@*****.**",
                UserName             = "******",
                NormalizedUserName   = "******",
                EmailConfirmed       = true,
                PhoneNumberConfirmed = true,
                SecurityStamp        = Guid.NewGuid().ToString("D")
            };


            if (!context.Users.Any(u => u.UserName == adminUser.UserName))
            {
                var password = new PasswordHasher <User>();
                var hashed   = password.HashPassword(adminUser, "admin1111");
                adminUser.PasswordHash = hashed;

                var userStore = new UserStore <User>(context);
                var result    = await userStore.CreateAsync(adminUser);
            }

            await AssignRoles(serviceProvider, adminUser.Email, roles);

            await context.SaveChangesAsync();
        }
Ejemplo n.º 2
0
        public async Task <IdentityResult> UpdatePermissionsAsync(Role role, List <string> permissions)
        {
            if (role == null)
            {
                throw new ArgumentNullException(nameof(role));
            }
            if (permissions == null)
            {
                throw new ArgumentNullException(nameof(permissions));
            }

            // 移除旧的权限Claim数据
            var claims = await GetClaimsAsync(role);

            if (claims != null)
            {
                var permissionClaims = claims.Where(w => w.Type == AppConstants.ClaimTypes.Permission).ToList();
                foreach (var permissionClaim in permissionClaims)
                {
                    await RoleStore.RemoveClaimAsync(role, permissionClaim, CancellationToken);
                }
            }
            // 增加权限Claim
            foreach (var permission in permissions)
            {
                await RoleStore.AddClaimAsync(role, new Claim(AppConstants.ClaimTypes.Permission, permission), CancellationToken);
            }

            return(await UpdateRoleAsync(role));
        }
        private async Task AddRoleClaimAsyncHelper(IdentityRole role, Claim claim)
        {
            using (RoleStore <IdentityRole> store = roleFixture.CreateRoleStore())
            {
                using (RoleManager <IdentityRole> manager = roleFixture.CreateRoleManager(store))
                {
                    await manager.AddClaimAsync(role, claim);

                    await Assert.ThrowsAsync <ArgumentNullException>(() => store.AddClaimAsync(null, claim));

                    await Assert.ThrowsAsync <ArgumentNullException>(() => store.AddClaimAsync(role, null));

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

                    var claims = await manager.GetClaimsAsync(role);

                    Assert.Contains(claims, (c) => c.Value == claim.Value && c.Type == claim.Type);//, "Claim not found");
                }
            }
        }
Ejemplo n.º 4
0
    protected static async Task CreateUser(TContext context, TUser user)
    {
        using var userStore =
                  new UserStore <TUser, TRole, TContext, TKey, TUserClaim, TUserRole, TUserLogin, TUserToken, TRoleClaim>(context);
        using var roleStore = new RoleStore <TRole, TContext, TKey, TUserRole, TRoleClaim>(context);

        await userStore.CreateAsync(user);

        await userStore.AddClaimsAsync(user, new[] { new Claim("T1", "V1"), new Claim("T1", "V2"), new Claim("T2", "V3") });

        var adminRole = new TRole {
            NormalizedName = "admin", Name = "Admin"
        };
        await roleStore.CreateAsync(adminRole);

        await userStore.AddToRoleAsync(user, "admin");

        await roleStore.AddClaimAsync(adminRole, new Claim("AC1", "V1"));

        await roleStore.AddClaimAsync(adminRole, new Claim("AC2", "V1"));

        var moderatorRole = new TRole {
            NormalizedName = "moderator", Name = "Moderator"
        };
        await roleStore.CreateAsync(moderatorRole);

        await userStore.AddToRoleAsync(user, "moderator");

        await roleStore.AddClaimAsync(moderatorRole, new Claim("MC1", "V1"));

        await roleStore.AddClaimAsync(moderatorRole, new Claim("MC2", "V1"));

        await userStore.AddLoginAsync(user, new UserLoginInfo("ISCABBS", "DrDave", "SSHFTW"));

        await userStore.AddLoginAsync(user, new UserLoginInfo("Local", "EekyBear", "PPS"));

        await userStore.SetTokenAsync(user, "ISCABBS", "DrDave", "SSHFTW", CancellationToken.None);

        await context.SaveChangesAsync();
    }
        public async Task _02_CanDoCURD()
        {
            var role = new IdentityRole();

            role.Name           = "Role 1";
            role.NormalizedName = role.Name.ToUpperInvariant();
            var result = await store.CreateAsync(role, CancellationToken.None);

            Assert.True(result.Succeeded);
            Assert.IsNotEmpty(role.Id);
            Assert.IsNotEmpty(role.ConcurrencyStamp);

            role.Name           = "role 1 updated";
            role.NormalizedName = role.Name.ToUpperInvariant();
            result = await store.UpdateAsync(role, CancellationToken.None);

            Assert.True(result.Succeeded);

            role = await store.FindByIdAsync(role.Id, CancellationToken.None);

            Assert.AreEqual(role.Id, role.Id);
            Assert.AreEqual(role.Name, role.Name);

            var normalizedName = role.NormalizedName;

            role = await store.FindByNameAsync(normalizedName, CancellationToken.None);

            Assert.AreEqual(normalizedName, role.NormalizedName);

            var claim = new Claim("test", "test");

            await store.AddClaimAsync(role, claim, CancellationToken.None);

            var roleClaims = await store.GetClaimsAsync(role, CancellationToken.None);

            Assert.NotNull(roleClaims);
            Assert.True(roleClaims.Count > 0);

            await store.RemoveClaimAsync(role, claim, CancellationToken.None);

            roleClaims = await store.GetClaimsAsync(role, CancellationToken.None);

            Assert.NotNull(roleClaims);
            Assert.True(roleClaims.Count == 0);

            result = await store.DeleteAsync(role, CancellationToken.None);

            Assert.True(result.Succeeded);
        }
Ejemplo n.º 6
0
 public void ArgumentNullExceptions()
 {
     Assert.ThrowsAsync <ArgumentNullException>(() => _roleStore.FindByNameAsync(null, CancellationToken.None));
     Assert.ThrowsAsync <ArgumentNullException>(() => _roleStore.GetClaimsAsync(null, CancellationToken.None));
     Assert.ThrowsAsync <ArgumentNullException>(() => _roleStore.GetRoleNameAsync(null, CancellationToken.None));
     Assert.ThrowsAsync <ArgumentNullException>(() => _roleStore.SetRoleNameAsync(null, "x", CancellationToken.None));
     Assert.ThrowsAsync <ArgumentNullException>(() => _roleStore.SetRoleNameAsync(new ApplicationRole(), null, CancellationToken.None));
     Assert.ThrowsAsync <ArgumentNullException>(() => _roleStore.GetRoleIdAsync(null, CancellationToken.None));
     Assert.ThrowsAsync <ArgumentNullException>(() => _roleStore.GetNormalizedRoleNameAsync(null, CancellationToken.None));
     Assert.ThrowsAsync <ArgumentNullException>(() => _roleStore.CreateAsync(null, CancellationToken.None));
     Assert.ThrowsAsync <ArgumentNullException>(() => _roleStore.UpdateAsync(null, CancellationToken.None));
     Assert.ThrowsAsync <ArgumentNullException>(() => _roleStore.DeleteAsync(null, CancellationToken.None));
     Assert.ThrowsAsync <ArgumentNullException>(() => _roleStore.AddClaimAsync(null, new Claim("any", "thing"), CancellationToken.None));
     Assert.ThrowsAsync <ArgumentNullException>(() => _roleStore.AddClaimAsync(new ApplicationRole(), null, CancellationToken.None));
     Assert.ThrowsAsync <ArgumentNullException>(() => _roleStore.RemoveClaimAsync(null, new Claim("any", "thing"), CancellationToken.None));
     Assert.ThrowsAsync <ArgumentNullException>(() => _roleStore.RemoveClaimAsync(new ApplicationRole(), null, CancellationToken.None));
 }
Ejemplo n.º 7
0
        public static async void Initialize(IServiceProvider serviceProvider)
        {
            var context        = serviceProvider.GetService <IdentityDbContext>();
            var userRepository = new UserRepository();

            string[] roles = { "SuperAdmin" };

            foreach (string role in roles)
            {
                var roleStore = new RoleStore <IdentityRole>(context);

                if (!context.Roles.Any(r => r.Name == role))
                {
                    var identityResult = await roleStore.CreateAsync(new IdentityRole { Name = role, NormalizedName = role.ToUpper() });

                    var claims = new List <Claim>
                    {
                        new Claim("feature", "user.register"),
                        new Claim("feature", "user.assignClaim"),
                        new Claim("feature", "user.assignRole"),
                        new Claim("feature", "user.assignResource"),
                        new Claim("feature", "user.get"),
                        new Claim("feature", "role.create"),
                        new Claim("feature", "role.assignClaim"),
                        new Claim("feature", "merchant.list"),
                        new Claim("feature", "merchant.get"),
                        new Claim("feature", "merchant.update"),
                        new Claim("feature", "transaction.list"),
                        new Claim("feature", "transaction.getByMerchant"),
                        new Claim("feature", "transaction.getByBusiness"),
                        new Claim("feature", "identity.get"),
                        new Claim("feature", "identity.getRoles"),
                        new Claim("feature", "identity.getPermissions"),
                        new Claim("feature", "claim.list"),
                        new Claim("feature", "claim.details"),
                        new Claim("feature", "claim.create"),
                        new Claim("feature", "claim.edit"),
                        new Claim("feature", "role.list"),
                        new Claim("feature", "role.details"),
                        new Claim("feature", "role.create"),
                        new Claim("feature", "role.edit"),
                        new Claim("feature", "user.list"),
                        new Claim("feature", "user.details"),
                        new Claim("feature", "user.create"),
                        new Claim("feature", "user.edit"),
                    };

                    var identityRole = context.Roles.FirstOrDefault(r => r.Name == role);

                    claims.ForEach(async c =>
                    {
                        await roleStore.AddClaimAsync(identityRole, c);
                    });
                }
            }

            var user = new IdentityUser
            {
                Email                = "*****@*****.**",
                NormalizedEmail      = "*****@*****.**",
                UserName             = "******",
                NormalizedUserName   = "******",
                PhoneNumber          = "+923366633352",
                EmailConfirmed       = true,
                PhoneNumberConfirmed = true,
                SecurityStamp        = Guid.NewGuid().ToString("D")
            };

            if (!context.Users.Any(u => u.UserName == user.UserName))
            {
                var userStore = new UserStore <IdentityUser>(context);
                var result    = await userStore.CreateAsync(user);

                var identityUser = await userStore.FindByEmailAsync(user.Email);

                var adminUserId = 1;

                userRepository.Update(new User {
                    GuidRef = identityUser.Id, Id = adminUserId
                });
            }

            await AssignRolesAsync(serviceProvider, user.Email, roles);

            await context.SaveChangesAsync();
        }