public void Setup()
        {
            _plantProviderMock = new Mock <IPlantProvider>();
            _plantProviderMock.SetupGet(p => p.Plant).Returns(Plant1);

            _plantCacheMock = new Mock <IPlantCache>();
            _plantCacheMock.Setup(p => p.HasUserAccessToPlantAsync(Plant1, Oid)).Returns(Task.FromResult(true));
            _plantCacheMock.Setup(p => p.HasUserAccessToPlantAsync(Plant2, Oid)).Returns(Task.FromResult(true));

            var permissionCacheMock = new Mock <IPermissionCache>();

            permissionCacheMock.Setup(p => p.GetPermissionsForUserAsync(Plant1, Oid))
            .Returns(Task.FromResult <IList <string> >(new List <string> {
                Permission1_Plant1, Permission2_Plant1
            }));
            permissionCacheMock.Setup(p => p.GetProjectsForUserAsync(Plant1, Oid))
            .Returns(Task.FromResult <IList <string> >(new List <string> {
                Project1_Plant1, Project2_Plant1
            }));

            permissionCacheMock.Setup(p => p.GetPermissionsForUserAsync(Plant2, Oid))
            .Returns(Task.FromResult <IList <string> >(new List <string> {
                Permission1_Plant2
            }));
            permissionCacheMock.Setup(p => p.GetProjectsForUserAsync(Plant2, Oid))
            .Returns(Task.FromResult <IList <string> >(new List <string> {
                Project1_Plant2
            }));

            var loggerMock = new Mock <ILogger <ClaimsTransformation> >();

            _principalWithOid = new ClaimsPrincipal();
            var claimsIdentity = new ClaimsIdentity();

            claimsIdentity.AddClaim(new Claim(ClaimsExtensions.Oid, Oid.ToString()));
            _principalWithOid.AddIdentity(claimsIdentity);

            _dut = new ClaimsTransformation(
                _plantProviderMock.Object,
                _plantCacheMock.Object,
                permissionCacheMock.Object,
                loggerMock.Object);
        }
        public void AddDistinctionAsync_IfNotAdmin_ThrowsUnauthorizedAccessException()
        {
            //Arrange
            mockRepoWrapper
            .Setup(x => x.Distinction.CreateAsync(It.IsAny <Distinction>()));

            //Act
            ClaimsIdentity  claimsIdentity = new ClaimsIdentity();
            ClaimsPrincipal notAdmin       = new ClaimsPrincipal();

            claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "Htos`"));
            notAdmin.AddIdentity(claimsIdentity);

            //Assert
            Exception exception = Assert.ThrowsAsync(typeof(UnauthorizedAccessException),
                                                     async() => { await distinctionService.AddDistinctionAsync(It.IsAny <DistinctionDTO>(), notAdmin); });

            Assert.AreEqual("Attempted to perform an unauthorized operation.", exception.Message);
        }
Example #3
0
        public Task <ClaimsPrincipal> TransformAsync(ClaimsPrincipal p)
        {
            string        appCode    = _config.GetValue <string>("appCode");
            List <string> UserRights = new List <string>();

            lock (dbLock)
            {
                UserRights = _usermanager.GetUserRights(p?.Identity?.Name, appCode);
            }
            var claims = new List <Claim>();

            foreach (string item in UserRights)
            {
                claims.Add(new Claim(item, "true"));
            }

            p.AddIdentity(new ClaimsIdentity(claims));
            return(Task.FromResult(p));
        }
Example #4
0
        public async Task <Result <IAuthResponse> > SignIn(IAuthRequest request, ClaimsPrincipal principal)
        {
            try
            {
                Result <User> userResult = await _usersRepo.Get(
                    u => request.Email.Equals(u.Email, StringComparison.OrdinalIgnoreCase));

                User user = userResult.Data;
                if (user == null)
                {
                    userResult.AddError(ErrorCodes.AUTH_EMAIL_NOT_FOUND);
                    return(Result <IAuthResponse> .Error(userResult.ErrorCodes));
                }
                if (!user.Password.SequenceEqual(GetHash(request.Password)))
                {
                    userResult.AddError(ErrorCodes.AUTH_EMAIL_OR_PASSWORD_INCORRECT);
                    return(Result <IAuthResponse> .Error(userResult.ErrorCodes));
                }
                var claims = new Claim[]
                {
                    new Claim(ClaimTypes.Sid, user.Id.ToString())
                };
                var identity = new ClaimsIdentity(claims);
                principal.AddIdentity(identity);

                var now = DateTime.UtcNow;
                JwtSecurityToken token = new JwtSecurityToken(
                    issuer: _config.Issuer,
                    audience: _config.Audience,
                    claims: identity.Claims,
                    notBefore: now,
                    expires: now.Add(TimeSpan.FromHours(_config.Lifetime)),
                    signingCredentials: new SigningCredentials(_key, SecurityAlgorithms.HmacSha256));
                _logger.LogInformation($"User {user} signed in.");
                return(Result <IAuthResponse> .Success(
                           new AuthResponse(new JwtSecurityTokenHandler().WriteToken(token))));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }
            return(Result <IAuthResponse> .Error(ErrorCodes.UNEXPECTED));
        }
        public Task Invoke(HttpContext context)
        {
            const string authenticationHeaderName = "Authorization";
            const string tokenSchemeName          = "Bearer";


            var result = context.Request.Headers.TryGetValue(authenticationHeaderName, out var header);

            if (result)
            {
                result = AuthenticationHeaderValue.TryParse(header, out var authenticationHeader);

                if (result)
                {
                    var token = authenticationHeader.Parameter;
                    if (token != null && authenticationHeader.Scheme == tokenSchemeName)
                    {
                        var user = _authenticationService.Authenticate(token);

                        if (user != null)
                        {
                            var identity = new ClaimsIdentity();

                            var nameClaim  = new Claim(nameof(User.Name), user.Name);
                            var tokenClaim = new Claim(nameof(User.Token), user.Token);

                            identity.AddClaim(nameClaim);
                            identity.AddClaim(tokenClaim);

                            var principal = new ClaimsPrincipal();
                            principal.AddIdentity(identity);


                            context.User = new ClaimsPrincipal(principal);

                            return(_next(context));
                        }
                    }
                }
            }

            throw new AuthenticationException();
        }
Example #6
0
        private static async Task AddUserIdClaim(ClaimsPrincipal user, HttpContext ctx)
        {
            var userBusiness = ctx.RequestServices.GetService <IUserBusiness>();

            var email = user.Claims.First(c => c.Type == ClaimTypes.Email).Value;

            var userId = userBusiness.GetUserIdByEmail(email);

            if (userId == null)
            {
                userId = await CreateFirebaseUser(userBusiness, user, ctx);
            }

            var id = new ClaimsIdentity();

            id.AddClaim(new Claim("id", userId.Value.ToString()));

            user.AddIdentity(id);
        }
Example #7
0
        private AuthenticationTicket CloneTicket(AuthenticationTicket ticket, ClaimsPrincipal replacedPrincipal)
        {
            var principal    = replacedPrincipal ?? ticket.Principal;
            var newPrincipal = new ClaimsPrincipal();

            foreach (var identity in principal.Identities)
            {
                newPrincipal.AddIdentity(identity.Clone());
            }

            var newProperties = new AuthenticationProperties();

            foreach (var item in ticket.Properties.Items)
            {
                newProperties.Items[item.Key] = item.Value;
            }

            return(new AuthenticationTicket(newPrincipal, newProperties, ticket.AuthenticationScheme));
        }
Example #8
0
        public async void UpdateUserReturnUpdatedUserTest()
        {
            //Arrange
            User          u         = new User("1", "userName", "password", 1, 1, 1, "name", "surname", "address", "phoneNumber", "base64Profile", true);
            List <string> listRoles = new List <string>();

            listRoles.Add("rol1");
            listRoles.Add("rol2");

            ClaimsIdentity Identity = new ClaimsIdentity(new Claim[]
            {
                new Claim("id", "1"),
                new Claim("http://schemas.microsoft.com/identity/claims/tenantid", "test"),
                new Claim("http://schemas.microsoft.com/identity/claims/objectidentifier", Guid.NewGuid().ToString()),
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname", "test"),
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname", "test"),
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn", "test"),
            }, "test");

            ClaimsPrincipal reqUser = new ClaimsPrincipal();

            reqUser.AddIdentity(Identity);

            UserOutput uO = new UserOutput()
            {
                Id = "2", Username = "******", Name = "Name", Surname = "surname", PlantID = 1, Plant = "Plant", SectorID = 1, Sector = "Sector", JobID = 1, Job = "job", PhoneNumber = "phone", Address = "address", base64Profile = "base64", Roles = listRoles
            };

            var mockUserRepository = new Mock <IUserRepository>();
            var mockMapper         = new Mock <IMapper>();

            mockUserRepository.Setup(e => e.Update(It.IsAny <User>(), It.IsAny <List <string> >())).ReturnsAsync(u);
            mockMapper.Setup(e => e.Map <User, UserOutput>(It.IsAny <User>())).Returns(uO);

            var useCase = new UpdateUserUseCase(mockUserRepository.Object, mockMapper.Object);

            //Act
            var res = await useCase.Execute(reqUser, "1", "userName", "password", 1, 1, 1, "name", "surname", listRoles, "address", "phoneNumber", "base64Profile", true);

            //Assert
            Assert.IsType <UserOutput>(res);
        }
Example #9
0
        public void Should_Override_User_In_Owin_Environment()
        {
            //Given
            var fakeTokenValidator = A.Fake <ITokenValidator>();

            var secureuser     = new ClaimsPrincipal();
            var claimsIdentity = new ClaimsIdentity("Token");

            claimsIdentity.AddClaim(new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "DumbUser"));
            secureuser.AddIdentity(claimsIdentity);

            A.CallTo(() => fakeTokenValidator.ValidateUser(A <string> .Ignored))
            .Returns(secureuser);

            var owinhttps = GetStatelessAuth(GetNextFunc(), tokenValidator: fakeTokenValidator);

            //TODO Tidy on 3.8 Mono release
            var overriddenUser     = new ClaimsPrincipal();
            var overriddenIdentity = new ClaimsIdentity("Token");

            overriddenIdentity.AddClaim(new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "Administrator"));
            overriddenUser.AddIdentity(overriddenIdentity);

            var environment = new Dictionary <string, object>
            {
                { "owin.RequestHeaders", new Dictionary <string, string[]>()
                  {
                      { "Authorization", new[] { "mysecuretoken" } }
                  } },
                { "owin.RequestPath", "/" },
                { ServerUser, overriddenUser }
            };

            //When
            var task = owinhttps.Invoke(environment);

            //Then
            var user = environment[ServerUser] as ClaimsPrincipal;

            //TODO Tidy on 3.8 Mono release
            Assert.True(user.HasClaim(x => x.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" && x.Value == "DumbUser"));
        }
Example #10
0
        public IActionResult Index()
        {
            var claimsIdentity = (ClaimsIdentity)User.Identity;
            var claims         = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);


            claimsIdentity.AddClaim(new Claim(ClaimTypes.Sid, "id"));                                        //Enum.GetName(typeof(ERole), ERole.uye))
            claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, Enum.GetName(typeof(ERole), ERole.egitmen))); //Enum.GetName(typeof(ERole), ERole.uye))
                                                                                                             //claimsIdentity.AddClaim(new Claim(ClaimTypes.Role,"admin"));
            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal();

            claimsPrincipal.AddIdentity(claimsIdentity);
            string uyeid = User.Claims.FirstOrDefault(f => f.Type == System.Security.Claims.ClaimTypes.Sid).Value;

            var fromClaim = Convert.ToInt32(uyeid);

            // BURASINI KONTROL ET!!
            //  int fromClaim = (int)Convert.ToUInt32(claims.Value);
            CartVM = new CartVM()
            {
                Order    = new Order(),
                ListCart = rCart.GetAllLazy(u => u.MemberId == fromClaim, includeProperties: "Course").ToList()
            };
            CartVM.Order.OrderTotal = 0;
            //int frmV = Convert.ToInt32(claims.Value)
            CartVM.Order.member = rMember.GetBy(u => u.ID == fromClaim);

            foreach (var cart in CartVM.ListCart)
            {
                //Eklenecek
                cart.Price = GetPriceBaseOnQuantity(cart.Course);
                CartVM.Order.OrderTotal += cart.Price;
                cart.Course.Description  = ConvertToRawHtml(cart.Course.Description);

                if (cart.Course.Description.Length > 50)
                {
                    cart.Course.Description = cart.Course.Description.Substring(0, 49) + "...";
                }
            }

            return(View(CartVM));
        }
Example #11
0
        public async Task PatchUser_ValidCall()
        {
            var mock = AutoMock.GetLoose();
            var user = new UserUpdateDto();

            mock.Mock <IUserService>().Setup(x => x.UserForUpdate("id")).ReturnsAsync(user);
            var controller = mock.Create <UserController>();

            controller.ControllerContext = new ControllerContext {
                HttpContext = new DefaultHttpContext()
            };
            var claims = new ClaimsPrincipal();

            claims.AddIdentity(new ClaimsIdentity(new [] { new Claim(ClaimTypes.PrimarySid, "id") }));
            controller.ControllerContext.HttpContext.User = claims;

            var result = await controller.PatchUser(new JsonPatchDocument <UserUpdateDto>());

            Assert.IsType <OkResult>(result);
        }
Example #12
0
        /// <summary>
        /// add claims from db
        /// </summary>
        /// <param name="incommingPrincipal">principal from authenticateHttpMessageHandler</param>
        /// <returns>incommingPrincipal with new claims</returns>
        /// <exception>All exceptions will be caught in AuthenticateHttpMessageHandler</exception>"
        private ClaimsPrincipal AddClaimsToPrincipal(ClaimsPrincipal incommingPrincipal)
        {
            // get username from claims
            string username = incommingPrincipal.FindFirst(claim => claim.Type == "UserName").Value;

            // new identity for principal
            ClaimsIdentity ci = new ClaimsIdentity();

            // get all claims
            List <Claim> allClaims = GetClaims(username);

            // Add Claims to identity
            ci.AddClaims(allClaims);

            // store new identity in principal
            incommingPrincipal.AddIdentity(ci);

            // return principal with all claims
            return(incommingPrincipal);
        }
Example #13
0
        public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
        {
            var msClientPrincipalEncoded = WebOperationContext.Current?.IncomingRequest?.Headers["X-MS-CLIENT-PRINCIPAL"];

            if (msClientPrincipalEncoded == null)
            {
                return(incomingPrincipal);
            }

            byte[]            decodedBytes             = Convert.FromBase64String(msClientPrincipalEncoded);
            string            msClientPrincipalDecoded = System.Text.Encoding.Default.GetString(decodedBytes);
            MsClientPrincipal clientPrincipal          = JsonConvert.DeserializeObject <MsClientPrincipal>(msClientPrincipalDecoded);

            ClaimsPrincipal     principal = new ClaimsPrincipal();
            IEnumerable <Claim> claims    = clientPrincipal.Claims.Select(x => new Claim(x.Type, x.Value));

            principal.AddIdentity(new ClaimsIdentity(claims, clientPrincipal.AuthenticationType, clientPrincipal.NameType, clientPrincipal.RoleType));

            return(principal);
        }
Example #14
0
        Task <ClaimsPrincipal> IClaimsTransformation.TransformAsync(ClaimsPrincipal principal)
        {
            var userName = principal.Identity.Name;
            var ci       = Cacher.FindOrCreateValue(
                userName,
                () =>
            {
                var ci = new ClaimsIdentity("ulo");
                foreach (var c in Db.AspNetUserClaims.Where(c => c.User.UserName == userName).AsNoTracking())
                {
                    ci.AddClaim(new Claim(c.ClaimType, c.ClaimValue));
                }
                return(ci);
            },
                ConfigOptions.Value.ClaimsCacheTimeout);

            LogInformation("Loaded {claimCount} for {principal}", ci.Claims.Count(), userName);
            principal.AddIdentity(ci);
            return(Task.FromResult(principal));
        }
Example #15
0
        public void RoleCheckSingleDeny()
        {
            var identity = new ClaimsIdentity("Test");

            identity.AddClaim(new Claim(identity.RoleClaimType, "NotValidRole"));

            var user = new ClaimsPrincipal();

            user.AddIdentity(identity);

            var attributes = new AuthorizeAttribute[]
            {
                new AuthorizeAttribute()
                {
                    Roles = "Allow"
                }
            };

            Assert.False(HalcyonExtUtils.CheckRoles(user, attributes));
        }
Example #16
0
        public static T WithUser <T>(this T c) where
        T : ControllerBase
        {
            var user = new ClaimsPrincipal();

            user.AddIdentity(new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.NameIdentifier, "test")
            }));

            c.ControllerContext = new ControllerContext
            {
                HttpContext = new DefaultHttpContext()
                {
                    User = user
                }
            };

            return(c);
        }
Example #17
0
        public Task <ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        {
            System.Collections.Generic.IEnumerable <Claim> customClaims = principal.Claims.Where(c => _sourceClaimType.Equals(c.Type, StringComparison.OrdinalIgnoreCase));
            System.Collections.Generic.IEnumerable <Claim> roleClaims   = customClaims.SelectMany(c =>
            {
                return(c.Value.Split(' ').Select(s => new Claim(_roleType, s)));
            });

            if (!roleClaims.Any())
            {
                return(Task.FromResult(principal));
            }


            ClaimsPrincipal transformed   = new ClaimsPrincipal(principal);
            ClaimsIdentity  rolesIdentity = new ClaimsIdentity(roleClaims, _authType, null, _roleType);

            transformed.AddIdentity(rolesIdentity);
            return(Task.FromResult(transformed));
        }
Example #18
0
        public void RoleCheckMultipleOr()
        {
            var identity = new ClaimsIdentity("Test");

            identity.AddClaim(new Claim(identity.RoleClaimType, "Allow"));

            var user = new ClaimsPrincipal();

            user.AddIdentity(identity);

            var attributes = new AuthorizeAttribute[]
            {
                new AuthorizeAttribute()
                {
                    Roles = "Allow,OtherAllow"
                }
            };

            Assert.True(HalcyonExtUtils.CheckRoles(user, attributes));
        }
        public async Task UpdateAvailabilityRecordCommandHandler_Handle_AvailabilityRecordUpdated()
        {
            var accountId = Guid.NewGuid();

            var claimsIdentity = new ClaimsIdentity();

            claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, accountId.ToString()));
            var claimsPrincipal = new ClaimsPrincipal();

            claimsPrincipal.AddIdentity(claimsIdentity);

            var createAvailabilityRecordCommandHandler = new UpdateAvailabilityRecordCommandHandler(_availabilityRecordRepository,
                                                                                                    _claimConverter);

            var record = new AvailabilityRecord(accountId,
                                                "name",
                                                "url",
                                                200,
                                                "{}",
                                                1);

            await _availabilityRecordRepository.AddAsync(record,
                                                         CancellationToken.None);

            await _availabilityRecordRepository.UnitOfWork.SaveEntitiesAsync(CancellationToken.None);

            await createAvailabilityRecordCommandHandler.Handle(new UpdateAvailabilityRecordCommand(claimsPrincipal,
                                                                                                    record.Id,
                                                                                                    "test name",
                                                                                                    "http://google.com/",
                                                                                                    200,
                                                                                                    "{}",
                                                                                                    12), CancellationToken.None).ConfigureAwait(false);

            Assert.Equal(accountId, record.AccountId);
            Assert.Equal("test name", record.Name);
            Assert.Equal("http://google.com/", record.Url);
            Assert.Equal(200, record.ExpectedStatusCode);
            Assert.Equal("{}", record.ExpectedResponse);
            Assert.Equal(12, record.LogLifetimeThresholdInHours);
        }
Example #20
0
        public async Task <string> Login(LoginViewModel model)
        {
            var gambler = await _dbContext.Gamblers.Include(g => g.Roles).ThenInclude(r => r.Role).FirstOrDefaultAsync(g => g.UserName.Equals(model.UserName, StringComparison.InvariantCultureIgnoreCase));

            if (gambler == null)
            {
                return(null);
            }

            if (_passwordHasher.VerifyHashedPassword(gambler, gambler.Password, model.Password) != PasswordVerificationResult.Failed)
            {
                var roles = gambler.Roles.Select(r => r.Role);

                var rolesNames = string.Join(',', roles.Select(r => r.Name));

                var claims = new ClaimsPrincipal();

                claims.AddIdentity(new ClaimsIdentity(new List <Claim>
                {
                    new Claim("Id", gambler.Id.ToString()),
                    new Claim("DisplayName", gambler.DisplayName),
                    new Claim(ClaimsIdentity.DefaultNameClaimType, gambler.UserName),
                    new Claim(ClaimsIdentity.DefaultRoleClaimType, rolesNames)
                }, JwtBearerDefaults.AuthenticationScheme));

                var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_authSettings.Key));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                var token = new JwtSecurityToken(_authSettings.Issuer,
                                                 _authSettings.Audience,
                                                 claims: claims.Claims,
                                                 expires: DateTime.Now.AddMinutes(_authSettings.TokenLifeTimeInMinutes),
                                                 signingCredentials: creds);

                return(new JwtSecurityTokenHandler().WriteToken(token));
            }
            else
            {
                return(null);
            }
        }
        public void Should_GetCustomer_ForAuthorizedUser()
        {
            Customer testCustomer = new Customer
            {
                Id           = 1,
                UserId       = "test_user",
                Address1     = "Addr1",
                Address2     = "Addr2",
                Address3     = "Addr3",
                Address4     = "Addr4",
                Address5     = "Addr5",
                ContactEmail = "*****@*****.**",
                ContactPhone = "01234567898",
                FirstName    = "First",
                LastName     = "Last",
            };

            Mock <IUnitOfWork> mockUOW = new Mock <IUnitOfWork>();

            mockUOW.Setup(f => f.Customers.Get()).Returns(new[] { testCustomer }.AsQueryable());

            var userStore = new Mock <IUserStore <User> >();
            Mock <UserManager <User> > mockUserManager = new Mock <UserManager <User> >(userStore.Object, null, null, null, null, null, null, null, null);

            mockUserManager.Setup(f => f.GetUserId(It.IsAny <ClaimsPrincipal>())).Returns("test_user");
            mockUserManager.Setup(f => f.FindByNameAsync(It.IsAny <string>())).Returns(Task.FromResult(new User {
                Id = "test_user"
            }));

            CustomersController controller = new CustomersController(mockUOW.Object, mockUserManager.Object);
            var userClaimsIdentity         = new ClaimsPrincipal();

            userClaimsIdentity.AddIdentity(new ClaimsIdentity(new[] { new Claim("sub", "*****@*****.**") }));
            controller.ControllerContext.HttpContext = new DefaultHttpContext()
            {
                User = userClaimsIdentity
            };
            var customer = controller.GetCustomer();

            Assert.IsType <OkObjectResult>(customer);
        }
        /// <summary>
        /// Sets the user principal
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        private async Task SetPrincipal(TokenValidatedContext ctx)
        {
            if (ctx.Principal != null && ctx.Principal.Identity.IsAuthenticated)
            {
                try
                {
                    // Set user principal. Replace with your custom logic if needed
                    var identity = ctx.Principal.Identity as ClaimsIdentity;
                    var user     = new ClaimsPrincipal(identity);

                    user.AddIdentity(identity);
                    ctx.Principal = user;
                }
                catch (Exception ex)
                {
                    var logger = ctx.HttpContext.RequestServices.GetRequiredService <ILogger <JwtEventHelper> >();
                    logger.LogError(ex, "Setting user principal failed.");
                    ctx.Fail("Setting user principal failed.");
                }
            }
        }
        /// <summary>
        /// Clones a principal by filtering its identities.
        /// </summary>
        /// <param name="principal">The <see cref="ClaimsPrincipal"/> instance to filter.</param>
        /// <param name="filter">
        /// The delegate filtering the claims: return <c>true</c>
        /// to accept the claim, <c>false</c> to remove it.
        /// </param>
        public static ClaimsPrincipal Clone(this ClaimsPrincipal principal, Func <Claim, bool> filter)
        {
            if (principal == null)
            {
                throw new ArgumentNullException(nameof(principal));
            }

            if (filter == null)
            {
                throw new ArgumentNullException(nameof(filter));
            }

            var clone = new ClaimsPrincipal();

            foreach (var identity in principal.Identities)
            {
                clone.AddIdentity(identity.Clone(filter));
            }

            return(clone);
        }
Example #24
0
        public void GetDataPolicies_GivenFindableDataPolicyClaim_ReturnsEmptyList()
        {
            // Arrange
            user.AddIdentity(new ClaimsIdentity(
                                 new Claim[]
            {
                new Claim(ClaimTypes.Name, "example name"),
                new Claim(ClaimTypes.NameIdentifier, userId),
                new Claim("custom-claim", "example claim value"),
                new Claim("dataPolicy", "data policy value 1"),
                new Claim("dataPolicy", "data policy value 2")
            }));

            // Act
            List <string> lookupList = ClaimsHelper.GetDataPolicies(user);

            // Assert
            Assert.True(lookupList.Count == 2, "With findable datapolicy claim a populated list must be returned.");
            Assert.True(string.Compare(lookupList[0], "data policy value 1") == 0, $"Expected datapolicy value 'data policy value 1' not found. Found value: '{lookupList[0]}'.");
            Assert.True(string.Compare(lookupList[1], "data policy value 2") == 0, $"Expected datapolicy value 'data policy value 2' not found. Found value: '{lookupList[1]}'.");
        }
Example #25
0
        public void DeleteUserDistinctionAsync_IfAdmin_ThrowsNotImplementedException()
        {
            //Arrange
            mockRepoWrapper
            .Setup(x => x.UserDistinction.GetFirstAsync(It.IsAny <Expression <Func <UserDistinction, bool> > >(),
                                                        It.IsAny <Func <IQueryable <UserDistinction>, IIncludableQueryable <UserDistinction, object> > >()))
            .ReturnsAsync(() => null);

            //Act
            ClaimsIdentity  claimsIdentity = new ClaimsIdentity();
            ClaimsPrincipal Admin          = new ClaimsPrincipal();

            claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
            Admin.AddIdentity(claimsIdentity);

            //Assert
            Exception exception = Assert.ThrowsAsync(typeof(NotImplementedException),
                                                     async() => { await distinctionService.DeleteUserDistinctionAsync(It.IsAny <int>(), Admin); });

            Assert.AreEqual("The method or operation is not implemented.", exception.Message);
        }
Example #26
0
        public void DeleteUserDistinctionAsync_IfNotAdmin_ThrowsUnauthorizedAccessException()
        {
            //Arrange
            mockRepoWrapper
            .Setup(x => x.UserDistinction.GetFirstAsync(It.IsAny <Expression <Func <UserDistinction, bool> > >(),
                                                        It.IsAny <Func <IQueryable <UserDistinction>, IIncludableQueryable <UserDistinction, object> > >()))
            .ReturnsAsync(new UserDistinction());

            //Act
            ClaimsIdentity  claimsIdentity = new ClaimsIdentity();
            ClaimsPrincipal notAdmin       = new ClaimsPrincipal();

            claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "Htos`"));
            notAdmin.AddIdentity(claimsIdentity);

            //Assert
            Exception exception = Assert.ThrowsAsync(typeof(UnauthorizedAccessException),
                                                     async() => { await distinctionService.DeleteUserDistinctionAsync(It.IsAny <int>(), notAdmin); });

            Assert.AreEqual("Attempted to perform an unauthorized operation.", exception.Message);
        }
        public async Task SignIn(Guid usuarioId)
        {
            Usuario usuario            = _usuarioService.ObterPorId(usuarioId).Result;
            string  encryptedUsuarioId = _securityService.EncryptValue(usuario.Id);

            IEnumerable <Claim> claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Role, usuario.Grupo.Role),
                new Claim(ClaimTypes.NameIdentifier, encryptedUsuarioId)
            };

            ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            ClaimsPrincipal principal = new ClaimsPrincipal();

            principal.AddIdentity(claimsIdentity);

            CriarCacheUsuario(usuario);

            await _httpContextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
        }
        /// <summary>
        /// This creates an http context.
        /// </summary>
        /// <param name="cognitoUser">The Cognito User to link to the context</param>
        /// <param name="scheme">The scheme to signin the user into</param>
        /// <returns></returns>
        public static DefaultHttpContext MockContext(CognitoUser cognitoUser, string scheme)
        {
            var context       = new DefaultHttpContext();
            var authMock      = new Mock <IAuthenticationService>();
            var userPrincipal = new ClaimsPrincipal();

            userPrincipal.AddIdentity(new ClaimsIdentity(new List <Claim>()
            {
                new Claim(ClaimTypes.Name, cognitoUser.UserID),
                new Claim(providerKey, loginProvider),
                new Claim(ClaimTypes.AuthenticationMethod, providerKey)
            }));
            var authenticationTicket = new AuthenticationTicket(userPrincipal, scheme);
            var authenticateResult   = AuthenticateResult.Success(authenticationTicket);

            context.RequestServices = new ServiceCollection().AddSingleton(authMock.Object).BuildServiceProvider();
            authMock.Setup(a => a.AuthenticateAsync(context,
                                                    scheme)).Returns(Task.FromResult(authenticateResult)).Verifiable();

            return(context);
        }
        private async Task AddTokenClaimsToPrincipal(string authenticationScheme, ClaimsPrincipal principal, string tokenName)
        {
            var jwtToken = await HttpContext.GetTokenAsync("External", tokenName);

            if (!string.IsNullOrWhiteSpace(jwtToken))
            {
                var token          = new JwtSecurityToken(jwtToken);
                var claimsIdentity = new ClaimsIdentity(token.Claims, tokenName);

                // die OpenIdConnectOptions zum authenticationScheme ermittteln
                var options = _optionsFactory.Create(authenticationScheme);

                // Alle Claimsctions ausführen, diese löschen z.b. nicht benötigte Claims für Cookies.
                foreach (var action in options.ClaimActions)
                {
                    action.Run(null, claimsIdentity, null);
                }

                principal.AddIdentity(claimsIdentity);
            }
        }
        public void DeleteDistinctionAsync_IfAdmin_ThrowsArgumentNullException()
        {
            //Arrange
            mockRepoWrapper
            .Setup(x => x.Distinction.GetFirstAsync(It.IsAny <Expression <Func <Distinction, bool> > >(),
                                                    It.IsAny <Func <IQueryable <Distinction>, IIncludableQueryable <Distinction, object> > >()))
            .ReturnsAsync(nullDistinction);

            //Act
            ClaimsIdentity  claimsIdentity = new ClaimsIdentity();
            ClaimsPrincipal Admin          = new ClaimsPrincipal();

            claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
            Admin.AddIdentity(claimsIdentity);

            //Assert
            Exception exception = Assert.ThrowsAsync(typeof(ArgumentNullException),
                                                     async() => { await distinctionService.DeleteDistinctionAsync(It.IsAny <int>(), Admin); });

            Assert.AreEqual("Value cannot be null. (Parameter 'Distinction with 0 not found')", exception.Message);
        }