예제 #1
0
        // to use with DI see:
        // https://levelup.gitconnected.com/add-extra-user-claims-in-asp-net-core-web-applications-1f28c98c9ec6

        // https://stackoverflow.com/questions/42036810/asp-net-core-jwt-mapping-role-claims-to-claimsidentity
        private async Task <IList <Claim> > GetUserClaims(ApplicationUser user)
        {
            // https://tools.ietf.org/html/rfc7519#section-4

            IdentityOptions options = new IdentityOptions();
            List <Claim>    claims  = new List <Claim>
            {
                // (SUB) the principal that is the subject of the JWT
                new Claim(RegisteredClaims.Sub, user.UserName),

                // (JWT ID) provides a unique identifier for the JWT
                new Claim(RegisteredClaims.Jti, Guid.NewGuid().ToString()),

                // (NBF)
                new Claim(RegisteredClaims.Nbf, (DateTime.UtcNow - new TimeSpan(0, 0, 10)).ToString()),

                new Claim(options.ClaimsIdentity.UserIdClaimType, user.Id),
                new Claim(options.ClaimsIdentity.UserNameClaimType, user.UserName),

                // email and its confirmation
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress",
                          user.Email),
                // this claim name is arbitrary
                new Claim("vfd", user.EmailConfirmed? "true" : "false")
            };

            // claims from user claims
            IList <Claim> userClaims = await _userManager.GetClaimsAsync(user);

            claims.AddRange(userClaims);

            // claims from user roles
            IList <string> userRoles = await _userManager.GetRolesAsync(user);

            foreach (string userRole in userRoles)
            {
                claims.Add(new Claim(ClaimTypes.Role, userRole));
                MongoRole role = await _roleManager.FindByNameAsync(userRole);

                if (role != null && _roleManager.SupportsRoleClaims)
                {
                    IList <Claim> roleClaims = await _roleManager.GetClaimsAsync(role);

                    foreach (Claim roleClaim in roleClaims)
                    {
                        claims.Add(roleClaim);
                    }
                }
            }

            // claims from additional user properties
            // http://docs.oasis-open.org/imi/identity/v1.0/os/identity-1.0-spec-os.html#_Toc229451870

            claims.Add(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname",
                                 user.FirstName));
            claims.Add(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname",
                                 user.LastName));

            return(claims);
        }
예제 #2
0
        private async Task TestUserRoles()
        {
            if (await RoleManager.RoleExistsAsync(TestData.RoleName))
            {
                await RoleManager.DeleteAsync(await RoleManager.FindByNameAsync(TestData.RoleName));
            }

            IdentityResult roleResult = await RoleManager.CreateAsync(new MongoRole(TestData.RoleName));

            if (!roleResult.Succeeded || !await RoleManager.RoleExistsAsync(TestData.RoleName))
            {
                throw new Exception("Add role fails");
            }


            MongoRole role = await RoleManager.FindByNameAsync(TestData.RoleName);

            TestSiteUser user = await UserManager.FindByEmailAsync(TestData.Email);

            if (user == null)
            {
                user = new TestSiteUser {
                    UserName = TestData.Username, Email = TestData.Email
                };
                IdentityResult result = await UserManager.CreateAsync(user, TestData.Password);
            }

            IdentityResult addRoleResult = await UserManager.AddToRoleAsync(user, TestData.RoleName);

            if (!addRoleResult.Succeeded || !await UserManager.IsInRoleAsync(user, TestData.RoleName))
            {
                throw new Exception("Add role to user fails");
            }


            IdentityResult removeRoleResult = await UserManager.RemoveFromRoleAsync(user, TestData.RoleName);

            if (!removeRoleResult.Succeeded || await UserManager.IsInRoleAsync(user, TestData.RoleName))
            {
                throw new Exception("Remove user from role fails");
            }

            TestSiteUser userWithoutRole = await UserManager.FindByEmailAsync(TestData.Email);

            if (userWithoutRole.Roles.Any(r => r == role.Id.ToString()))
            {
                throw new Exception("Remove user from role fails");
            }
        }
예제 #3
0
        public async Task initDatabase(int nmbrScores)
        {
            var users = new[]
            {
                new GeoPointUser {
                    SecurityStamp = Guid.NewGuid().ToString(), UserName = "******"
                },
                new GeoPointUser {
                    SecurityStamp = Guid.NewGuid().ToString(), UserName = "******"
                },
                new GeoPointUser {
                    SecurityStamp = Guid.NewGuid().ToString(), UserName = "******"
                },
            };

            foreach (var u in users)
            {
                var user = await userMgr.FindByNameAsync(u.UserName);

                Debug.WriteLine(user);
                if (user == null)
                {
                    if (!(await roleMgr.RoleExistsAsync("Admin")))
                    {
                        var role = new MongoRole("Admin");
                        await roleMgr.CreateAsync(role);
                    }
                    var userResult = await userMgr.CreateAsync(u, "P@ssw0rd");

                    var roleResult = await userMgr.AddToRoleAsync(u, "Admin");

                    if (!userResult.Succeeded || !roleResult.Succeeded)
                    {
                        throw new InvalidOperationException("Failed to build user and roles");
                    }
                }
            }
            if (!mongoDBContext.CollectionExistsAsync("scores").Result)
            {
                List <string> AreaList = new List <string> {
                    "EUROPE", "AFRICA", "SOUTH-AMERICA", "NORTH-AMERICA", "AUSTRALIA"
                };
                for (var i = 0; i < nmbrScores; i++)
                {
                    DateTime date = DateTime.UtcNow.AddDays(-new Random().Next(7));
                    date = date.AddMinutes(-new Random().Next(60));
                    date = date.AddHours(-new Random().Next(24));
                    date = date.AddSeconds(-new Random().Next(60));
                    Debug.WriteLine(date.ToString());

                    await scoreRepo.CreateAsync(new Score
                    {
                        Value     = new Random().Next(30),
                        Area      = AreaList[new Random().Next(AreaList.Count)],
                        User      = users[new Random().Next(users.Length)],
                        TimeSpan  = new Random().Next(30),
                        TimeStamp = date
                    });
                }
            }
        }