public void IdentityBasicOperatorTest()
        {
            // rule DTO
            var car = new CarDTO
            {
                Make = "Ford",
                Year = 2010,
                Model = "Expedition",
                AskingPrice = 10000.0000m,
                SellingPrice = 9000.0000m
            };

            // programatic mix in of claims rule and rule against the DTO user
            var carRule1 = new Rule("Year", "2010", "GreaterThanOrEqual");
            var claimRule = new Rule("@User", "S-1-5-21-2493390151-660934664-2262481224-513", "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid");
            var re = new IdentityRuleEngine();
            // Compile the rules as a seperate step
            Expression<Func<CarDTO, IClaimsPrincipal, bool>> carRule1Expression = re.GetExpression<CarDTO>(carRule1);
            Expression<Func<CarDTO, IClaimsPrincipal, bool>> claimRuleExpression = re.GetExpression<CarDTO>(claimRule);
            Expression<Func<CarDTO, IClaimsPrincipal, bool>> compositeRule = carRule1Expression.Or(claimRuleExpression);

            // invoke the rules as a third step
            IClaimsPrincipal id = new ClaimsPrincipal(System.Threading.Thread.CurrentPrincipal);
            Assert.AreEqual(true,compositeRule.Compile()(car,id));
        }
        public static bool CheckAccess(ClaimsPrincipal principal, string action, params string[] resources)
        {
            var context = CreateAuthorizationContext(
                principal,
                action,
                resources);

            return CheckAccess(context);
        }
Beispiel #3
0
        private static void MockUserPrincipal(HttpContextBase httpContext, string userName)
        {
            var claimsIdentity = new ClaimsIdentity(AuthenticationTypes.Federation, ClaimTypes.Name, ClaimTypes.Role);
            claimsIdentity.Claims.Add(new Claim(ClaimTypes.Name, userName));

            var claimsPrincipal = new ClaimsPrincipal(new[] { claimsIdentity });
            httpContext.User = (IPrincipal)claimsPrincipal;

            FormsAuthentication.SetAuthCookie(userName, true);
        }
 protected void _login_Authenticate(object sender, AuthenticateEventArgs e)
 {
     FormsAuthentication.SetAuthCookie(_login.UserName, false);
                 var claims = new List<Claim>();
                 claims.Add(new Claim(System.IdentityModel.Claims.ClaimTypes.Name, _login.UserName));
                 List<ClaimsIdentity> identity = new List<ClaimsIdentity>();
                 identity.Add(new ClaimsIdentity(claims,"UserName"));
                 ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentityCollection(identity));
                 var querystring = Request.QueryString.ToString();
                 HttpContext.Current.Response.Redirect("/mysts.ashx?"+ querystring);
 }
        /// <summary>
        /// Checks the authorization policy.
        /// </summary>
        /// <param name="resource">The resource.</param>
        /// <param name="action">The action.</param>
        /// <param name="principal">The principal.</param>
        /// <returns>true when authorized, otherwise false</returns>
        public static bool CheckAccess(string resource, string action, ClaimsPrincipal principal)
        {
            Contract.Requires(!String.IsNullOrEmpty(resource));
            Contract.Requires(!String.IsNullOrEmpty(action));
            Contract.Requires(principal != null);


            var context = new AuthorizationContext(principal, resource, action);

            return AuthorizationManager.CheckAccess(context);
        }
        private bool CheckOwnership(int id, ClaimsPrincipal principal)
        {
            var oldConsultant = _repository.GetAll().FirstOrDefault(c => c.ID == id);

            if (oldConsultant == null)
            {
                return true;
            }

            // check if client is allowed to update consultant
            // only the record creator can update
            return oldConsultant.Owner.Equals(principal.Identity.Name);
        }
        public void TestCreateToReadyMultiplePotentialOwners()
        {
            IdentityId initiatorId = new IdentityId();
            IdentityId potentialOwnerOne = new IdentityId();
            IdentityId potentialOwnerTwo = new IdentityId();
            IdentityId businessAdminId = new IdentityId();
            IPrincipal initiator = new ClaimsPrincipal(initiatorId.GetIdentity());
            _mapStorage[potentialOwnerOne.Id] = new Account(potentialOwnerOne, "s-1-2-3-4-5", "auth", AccountType.User);
            _mapStorage[potentialOwnerTwo.Id] = new Account(potentialOwnerTwo, "s-1-2-3-4-5", "auth", AccountType.User);
            _mapStorage[businessAdminId.Id] = new Account(businessAdminId, "s-55-2-3-4-5", "auth", AccountType.User);

            ILoggingService loggingService = SetupLoggerMock(new List<TaskHistoryEvent> {
                                                                     new TaskHistoryEvent{
                                                                         Event = "Create",
                                                                         OldStatus = TaskStatus.None,
                                                                         NewStatus = TaskStatus.Created,
                                                                         OldPriority = Priority.Normal,
                                                                         NewPriority = Priority.Normal,
                                                                         Comment = "",
                                                                         TimeStamp = DateTime.UtcNow,
                                                                         UserId = initiator.Identity.GetMappedId()}
            });
            Thread.CurrentPrincipal = initiator;
            Task task = new Task(new TaskId(), TaskStatus.Created, string.Empty,
                                 string.Empty, Priority.Normal, false,
                                 DateTime.UtcNow, initiator.Identity,
                                 null, null, null)
            {
                LoggingService = loggingService
            };
            Assert.AreEqual(TaskStatus.Created, task.Status);
            task.PotentialOwners.Add(potentialOwnerOne.GetIdentity());
            task.PotentialOwners.Add(potentialOwnerTwo.GetIdentity());
            task.BusinessAdministrators.Add(businessAdminId.GetIdentity());
            Assert.IsNotNull(task);
            Assert.AreEqual(TaskStatus.Created, task.Status);
            IPrincipal businessAdmin = new ClaimsPrincipal(businessAdminId.GetIdentity());
            Thread.CurrentPrincipal = businessAdmin;
            task.Activate();
            Assert.AreEqual(TaskStatus.Ready, task.Status);
            Assert.IsNull(task.ActualOwner);
            Assert.IsNotNull(task.History);
            Assert.AreEqual(2, task.History.Count());
            TaskHistoryEvent history = task.History.ElementAt(0);
            Assert.IsNotNull(history);
            Assert.AreEqual(TaskStatus.None, history.OldStatus);
            Assert.AreEqual(TaskStatus.Created, history.NewStatus);
            Assert.AreEqual(initiator.Identity.GetMappedId(), history.UserId);
            history = task.History.ElementAt(1);
            Assert.IsNotNull(history);
        }
Beispiel #8
0
        private static void WriteCookie(AMSAdmin user, string timeOffsetValue)
        {
            SessionAuthenticationModule sam = (SessionAuthenticationModule)
                HttpContext.Current.ApplicationInstance.Modules["SessionAuthenticationModule"];

            IClaimsPrincipal principal =
               new ClaimsPrincipal(new GenericPrincipal(new GenericIdentity(user.LogonName), null));

            principal.Identities[0].Claims.Add(new Claim("TimeOffset", timeOffsetValue));
            principal.Identities[0].Claims.Add(new Claim("AMSAdminID", user.UserID));
            principal.Identities[0].Claims.Add(new Claim("AMSAdminName", user.Name));

            SessionSecurityToken token = sam.CreateSessionSecurityToken(principal, null, DateTime.Now, DateTime.Now.AddMinutes(60), false);

            sam.WriteSessionTokenToCookie(token);
        }
        public override bool CheckAccess(OperationContext operationContext)
        {
            int index = operationContext.RequestContext.RequestMessage.Headers.FindHeader("Security", WSSecurity10Constants.Namespace);
            if (index < 0)
            {
                return false;
            }

            var securityHeader = operationContext.RequestContext.RequestMessage.Headers.GetReaderAtHeader(index);

            var configuration = new ServiceConfiguration(true);

            securityHeader.Read();
            if (!configuration.SecurityTokenHandlers.CanReadToken(securityHeader))
                return false;

            if (configuration.ServiceCertificate != null)
            {
                SecurityToken xtoken;

                using (var xprovider = new X509SecurityTokenProvider(configuration.ServiceCertificate))
                {
                    xtoken = xprovider.GetToken(new TimeSpan(10, 1, 1));
                }

                var outOfBandTokens = new Collection<SecurityToken>();
                outOfBandTokens.Add(xtoken);

                configuration.SecurityTokenHandlers[typeof(EncryptedSecurityToken)].Configuration.ServiceTokenResolver =
                    SecurityTokenResolver.CreateDefaultSecurityTokenResolver(new ReadOnlyCollection<SecurityToken>(outOfBandTokens), false);
            }

            SecurityToken token = configuration.SecurityTokenHandlers.ReadToken(securityHeader);
            if (configuration.CertificateValidationMode == X509CertificateValidationMode.None)
            {
                configuration.CertificateValidator = X509CertificateValidator.None;
            }

            var claimsCollection = configuration.SecurityTokenHandlers.ValidateToken(token);

            IClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsCollection);

            SetPrincipal(operationContext, claimsPrincipal);

            return true;
        }
        public void TestCreateState()
        {
            IdentityId initiatorId = new IdentityId();
            IPrincipal initiator = new ClaimsPrincipal(initiatorId.GetIdentity());

            Task task = new Task(new TaskId(), TaskStatus.Created, string.Empty,
                                 string.Empty, Priority.Normal, false,
                                 DateTime.UtcNow, initiator.Identity,
                                 null, null, null);

            Thread.CurrentPrincipal = initiator;
            Assert.IsNotNull(task);
            Assert.AreEqual(TaskStatus.Created, task.Status);
            Assert.IsNull(task.ActualOwner);
            Assert.IsNotNull(task.Initiator);
            Assert.AreEqual(initiator.Identity, task.Initiator);
            Assert.AreEqual(Priority.Normal, task.Priority);
            Assert.AreEqual(TaskStatus.Created, task.Status);
        }
        public void IdentityTupleBasicOperatorTest()
        {
            // rule DTO
            var car = new CarDTO
            {
                Make = "Ford",
                Year = 2010,
                Model = "Expedition",
                AskingPrice = 10000.0000m,
                SellingPrice = 9000.0000m
            };

            var salesperson = new SalesPersonDTO
            {
                State = "PA",
                IsManager = true,
                MaximumDiscount = 1000.0000m
            };

            // programatic mix in of claims rule and rule against the DTO for Car and SalesPerson
            var carRule1 = new Rule("Year", "2010", "GreaterThanOrEqual","CarDTO");
            var claimRule = new Rule("@User", "S-1-5-21-2493390151-660934664-2262481224-513", "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid");
            var salePersonRule1 = new Rule("State", "PA", "Equals","SalesPersonDTO");
            var salePersonRule2 = new Rule("IsManager", "true", "Equals", "SalesPersonDTO");

            var re = new IdentityTupleRuleEngine();

            // build Some Expressions
            Expression<Func<CarDTO, SalesPersonDTO,IClaimsPrincipal, bool>> carRule1Expression = re.GetExpression<CarDTO,SalesPersonDTO>(carRule1);
            Expression<Func<CarDTO, SalesPersonDTO, IClaimsPrincipal, bool>> claimRuleExpression = re.GetExpression<CarDTO, SalesPersonDTO>(claimRule);
            Expression<Func<CarDTO, SalesPersonDTO, IClaimsPrincipal, bool>> sp1Expression = re.GetExpression<CarDTO, SalesPersonDTO>(salePersonRule1);
            Expression<Func<CarDTO, SalesPersonDTO, IClaimsPrincipal, bool>> sp2Expression = re.GetExpression<CarDTO, SalesPersonDTO>(salePersonRule2);

            Expression<Func<CarDTO, SalesPersonDTO, IClaimsPrincipal, bool>> coumpoundExpr =
                carRule1Expression.Or(claimRuleExpression).Or(sp1Expression).Or(sp2Expression);

            IClaimsPrincipal id = new ClaimsPrincipal(System.Threading.Thread.CurrentPrincipal);
            Assert.AreEqual(true, coumpoundExpr.Compile()(car,salesperson,id));
        }
         public override bool CheckAccess(OperationContext operationContext)
        {
            HttpRequestMessageProperty httpRequestMessage;
            object httpRequestMessageObject;

            if (operationContext.RequestContext.RequestMessage.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
            {
                httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
                if (string.IsNullOrEmpty(httpRequestMessage.Headers["Authorization"]))
                {
                    return false;
                }

                if (!httpRequestMessage.Headers["Authorization"].StartsWith("Bearer "))
                {
                    return false;
                }
                
                string jwt = httpRequestMessage.Headers["Authorization"].Split(' ')[1];
                if (string.IsNullOrEmpty(jwt))
                {
                    return false;
                }
                
                var key = Convert.FromBase64String(SymmetricKey.Replace("_", "/").Replace("-", "+"));
                Dictionary<string, object> json = JWT.JsonWebToken.DecodeToObject(jwt, key, verify: true, checkExpiration: true, audience: AllowedAudience, issuer: AllowedIssuer) as Dictionary<string, object>;
                var claims = json.Where(kv => kv.Value != null)
                                 .Select(c => new Claim(c.Key, c.Value.ToString())).ToList();

                claims.Add(new Claim(ClaimTypes.Name, GetClaimWithFallback(claims, "name", "sub")));
                IClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity[] { new ClaimsIdentity(claims) });

                SetPrincipal(operationContext, claimsPrincipal);

                return true;
            }

            return false;
        }
        public void IdentityLoadFromFile()
        {
            // rule DTO
            var car = new CarDTO
            {
                Make = "Ford",
                Year = 2010,
                Model = "Expedition",
                AskingPrice = 10000.0000m,
                SellingPrice = 9000.0000m
            };

            var re = new IdentityRuleEngine();

            // Load all rules applied to the user type.
            XmlDocument xd = new XmlDocument();
            xd.Load(@"C:\development\RuleEngine\TinyTuleEngineUnitTest\IdentityRuleEngineTest\RuleSetBasicIdentity.xml");
            re.LoadRulesFromElementList<CarDTO>(xd, "/rules/rule");

            Func<CarDTO, IClaimsPrincipal, bool> fordSaleApprover = re.GetRule<CarDTO>("FordSaleApprover").Compile();
            IClaimsPrincipal id = new ClaimsPrincipal(System.Threading.Thread.CurrentPrincipal);
            Assert.AreEqual(true, fordSaleApprover(car, id));
        }
Beispiel #14
0
 public GridController(UserManager <AppUser> userManager, ApplicationDbContext appDbContext, IHttpContextAccessor httpContextAccessor)
 {
     _caller       = httpContextAccessor.HttpContext.User;
     _appDbContext = appDbContext;
 }
 public static string GetUsername(this ClaimsPrincipal user)
 {
     return(user.FindFirst(ClaimTypes.Name)?.Value);
 }
 public static List <string> ClaimRoles(this ClaimsPrincipal claimsPrincipal)
 {
     return(claimsPrincipal.Claims(ClaimTypes.Role));
 }
 public string GetUserName(ClaimsPrincipal claims)
 {
     return GetClaimValue(claims, "user");
 }
        public static AuthorizationContext CreateAuthorizationContext(ClaimsPrincipal principal, string action, params string[] resources)
        {
            var actionClaims = new Collection<Claim>
            {
                new Claim(ActionType, action)
            };

            var resourceClaims = new Collection<Claim>();

            if (resources != null && resources.Length > 0)
            {
                resources.ToList().ForEach(ar => resourceClaims.Add(new Claim(ResourceType, ar)));
            }

            return new AuthorizationContext(
                principal,
                resourceClaims,
                actionClaims);
        }
        public async Task <IActionResult> Login(string username, string password)
        {
            if (string.IsNullOrEmpty(username))
            {
                ViewData["LoginResult"] = "Please enter username.";
                return(View());
            }

            if (string.IsNullOrEmpty(password))
            {
                ViewData["LoginResult"] = "Please enter password.";
                return(View());
            }



            AbstractUserDto checkUser = new UserDto();

            checkUser = await _userEntity.SignInUser(username, password);

            if (checkUser == null || checkUser.Id <= 0)
            {
                ViewData["LoginResult"] = "Wrong username/password. Try again.";
                return(View());
            }



            if (checkUser.Username == username &&
                checkUser.Password == password &&
                checkUser.IsActive == 1)
            {
                var userIdentity = new ClaimsIdentity("Identity");
                userIdentity.Label = "Identity";
                userIdentity.AddClaim(new Claim(ClaimTypes.Name, checkUser.Username));
                userIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, checkUser.Id.ToString()));
                userIdentity.AddClaim(new Claim(ClaimTypes.Country, ""));
                userIdentity.AddClaim(new Claim(ClaimTypes.Email, checkUser.Email));
                userIdentity.AddClaim(new Claim(ClaimTypes.Spn, checkUser.Image));


                userIdentity.AddClaim(new Claim(ClaimTypes.Role, "User"));
                if (checkUser.IsAdmin == 1)
                {
                    userIdentity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
                }


                ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);


                await HttpContext.SignInAsync(principal);
            }
            else
            {
                ViewData["LoginResult"] = "We are unable to log you in. Please contact administrators.";
                return(View());
            }


            return(RedirectPermanent("/"));
        }
        public static List <string> Claims(this ClaimsPrincipal claimsPrincipal, string claimType)
        {
            var result = claimsPrincipal.FindAll(claimType).Select(x => x.Value).ToList();

            return(result);
        }
 public static int GetUserId(this ClaimsPrincipal user)
 {
     // NameIdentifier -> represents the NameId property
     return(int.Parse(user.FindFirst(ClaimTypes.NameIdentifier)?.Value));
 }
Beispiel #22
0
 public PolicyTagHelper(IAuthorizationService authService, IHttpContextAccessor httpContextAccessor)
 {
     _authService = authService;
     _principal   = httpContextAccessor.HttpContext.User;
 }
Beispiel #23
0
 public bool UserIsLoggedIn(ClaimsPrincipal user)
 {
     return(true);
 }
Beispiel #24
0
 public static string GetStoreId(this ClaimsPrincipal principal)
 {
     return(principal.Claims.Where(c => c.Type == Claims.OwnStore).Select(c => c.Value).FirstOrDefault());
 }
 public static string GetSubjectClaim(this ClaimsPrincipal claimsPrincipal) =>
 claimsPrincipal.Claims.SingleOrDefault(c => c.Type == "sub")?.Value;
Beispiel #26
0
        public int GetUserID(ClaimsPrincipal user)
        {
            var userID = UserManager.GetUserId(user);

            return(int.Parse(userID));
        }
 public bool IsAdmin(ClaimsPrincipal claims)
 {
     return GetClaimValue(claims, "is_admin") == "true";
 }
Beispiel #28
0
        public async Task <UserSM> GetUserAsync(ClaimsPrincipal principal)
        {
            var applicationUser = await _userManager.GetUserAsync(principal);

            return(Mapper.Map <UserSM>(applicationUser));
        }
 public Task SignInAsync(HttpContext context, string scheme, ClaimsPrincipal principal, AuthenticationProperties properties)
 {
     throw new System.NotImplementedException();
 }
 public Task <AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object resource, string policyName)
 => Task.FromResult(AuthorizationResult.Failed());
        /// <summary>
        /// Searches the 'Authorization' header for a 'Bearer' token.
        /// </summary>
        /// <returns></returns>
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            string token = null;

            try
            {
                // Give application opportunity to find from a different location, adjust, or reject token
                var messageReceivedContext = new MessageReceivedContext(Context, Scheme, Options);

                // event can set the token
                await Events.MessageReceived(messageReceivedContext);

                if (messageReceivedContext.Result != null)
                {
                    return(messageReceivedContext.Result);
                }

                // If application retrieved token from somewhere else, use that.
                token = messageReceivedContext.Token;

                if (string.IsNullOrEmpty(token))
                {
                    string authorization = Request.Headers["Authorization"];

                    // If no authorization header found, nothing to process further
                    if (string.IsNullOrEmpty(authorization))
                    {
                        return(AuthenticateResult.NoResult());
                    }

                    if (authorization.StartsWith("FakeBearer ", StringComparison.OrdinalIgnoreCase))
                    {
                        token = authorization.Substring("FakeBearer ".Length).Trim();
                    }

                    // If no token found, no further work possible
                    if (string.IsNullOrEmpty(token))
                    {
                        return(AuthenticateResult.NoResult());
                    }
                }

                var tokenFromBase64 = Convert.FromBase64String(token);
                Dictionary <string, dynamic> tokenDecoded = JsonConvert.DeserializeObject <Dictionary <string, dynamic> >(Encoding.UTF8.GetString(tokenFromBase64));

                ClaimsIdentity id = new ClaimsIdentity("Identity.Application", "name", "role");

                foreach (var td in tokenDecoded)
                {
                    if (td.Key == "sub")
                    {
                        id.AddClaim(new Claim("sub", td.Value.ToString()));
                        if (!tokenDecoded.Any(c => c.Key == "name"))
                        {
                            id.AddClaim(new Claim("name", td.Value.ToString()));
                        }
                    }
                    else
                    {
                        if (td.Value is string)
                        {
                            id.AddClaim(new Claim(td.Key, td.Value));
                        }
                        else if (td.Value is IEnumerable)
                        {
                            foreach (string subValue in td.Value)
                            {
                                id.AddClaim(new Claim(td.Key, subValue));
                            }
                        }
                        else
                        {
                            throw new Exception("Unknown type");
                        }
                    }
                }

                ClaimsPrincipal principal = new ClaimsPrincipal(id);

                var tokenValidatedContext = new TokenValidatedContext(Context, Scheme, Options)
                {
                    Principal = principal
                };

                await Events.TokenValidated(tokenValidatedContext);

                if (tokenValidatedContext.Result != null)
                {
                    return(tokenValidatedContext.Result);
                }

                if (Options.SaveToken)
                {
                    tokenValidatedContext.Properties.StoreTokens(new[]
                    {
                        new AuthenticationToken {
                            Name = "access_token", Value = token
                        }
                    });
                }

                tokenValidatedContext.Success();
                return(tokenValidatedContext.Result);
            }
            catch (Exception ex)
            {
                var authenticationFailedContext = new AuthenticationFailedContext(Context, Scheme, Options)
                {
                    Exception = ex
                };

                await Events.AuthenticationFailed(authenticationFailedContext);

                if (authenticationFailedContext.Result != null)
                {
                    return(authenticationFailedContext.Result);
                }

                throw;
            }
        }
 public Task <AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object resource, IEnumerable <IAuthorizationRequirement> requirements)
 => Task.FromResult(AuthorizationResult.Failed());
        public virtual string CreateSessionToken(ClaimsPrincipal principal)
        {
            var handler = Configuration.SessionToken.SecurityTokenHandler;

            var descriptor = new SecurityTokenDescriptor
            {
                AppliesToAddress = Configuration.SessionToken.Audience.AbsoluteUri,
                TokenIssuerName = Configuration.SessionToken.IssuerName,
                SigningCredentials = new HmacSigningCredentials(Configuration.SessionToken.SigningKey),
                Subject = principal.Identities.First()
            };

            var token = handler.CreateToken(descriptor);
            return handler.WriteToken(token);
        }
        public void TestSuspendedToReversedActualOwner()
        {
            IdentityId actualId = new IdentityId();
            ILoggingService loggingService = SetupLoggerMock(new List<TaskHistoryEvent>());
            Task task = new Task(
                         new TaskId(), TaskStatus.Reserved, string.Empty,
                         string.Empty, Priority.Normal, false,
                         DateTime.UtcNow, new IdentityId().GetIdentity(),
                         DateTime.UtcNow, null, actualId.GetIdentity())
            {
                LoggingService = loggingService
            };
            IPrincipal actualOwner = new ClaimsPrincipal(actualId.GetIdentity());
            Thread.CurrentPrincipal = actualOwner;
            task.Suspend();
            Assert.AreEqual(TaskStatus.Suspended, task.Status);
            Assert.AreEqual(actualId.GetIdentity(), task.ActualOwner);
            task.Resume();
            Assert.AreEqual(TaskStatus.Reserved, task.Status);
            Assert.AreEqual(actualId.GetIdentity(), task.ActualOwner);

            Assert.IsNotNull(task.History);
            Assert.AreEqual(2, task.History.Count());
            TaskHistoryEvent history = task.History.ElementAt(0);
            Assert.IsNotNull(history);
            Assert.AreEqual(TaskStatus.Reserved, history.OldStatus);
            Assert.AreEqual(TaskStatus.Suspended, history.NewStatus);
            Assert.AreEqual(actualId, history.UserId);
            history = task.History.ElementAt(1);
            Assert.IsNotNull(history);
            Assert.AreEqual(TaskStatus.Suspended, history.OldStatus);
            Assert.AreEqual(TaskStatus.Reserved, history.NewStatus);
            Assert.AreEqual(actualId, history.UserId);
        }
Beispiel #35
0
 private readonly ClaimsPrincipal _claimsPrincipal; public GlobalRouting(ClaimsPrincipal claimsPrincipal)
 {
     _claimsPrincipal = claimsPrincipal;
 }
 /// <summary>
 /// Check if the user is a member if the group
 /// </summary>
 /// <param name="user"></param>
 /// <param name="group"></param>
 /// <returns></returns>
 public static bool IsInGroup(this ClaimsPrincipal user, string group)
 {
     return(user.HasClaim(c => c.Type == ClaimTypes.GroupSid && c.Value.Equals(group, StringComparison.OrdinalIgnoreCase)));
 }
        /// <summary>
        /// Creates a ClaimsPrincipal from the specified user data, sets the current HTTP context and thread principal
        /// and writes a session cookie from the resulting SessionSecurityToken using the specified parameters.
        /// </summary>
        /// <param name="user">The user data that will be used to create the claims for the ClaimsPrincipal. 
        /// Array values are converted to multiple claims with the same key.</param>
        /// <param name="context">An application defined context string.</param>
        /// <param name="domain">The domain used for the session cookie.</param>
        /// <param name="path">The virtual path used for the session cookie.</param>
        /// <param name="requireSsl">Indicates if the session cookie should only be used with SSL.</param>
        /// <param name="httpOnly">Indicates whether the session cookie should be hidden from client script.</param>
        /// <param name="cookieName">Indicates the name of the session cookie.</param>
        /// <param name="sessionCookieLifetime">The lifetime for the sesion cookie. A null value indicates no expiration.</param>
        /// <param name="persistent">Indicates if the user agent should persist the session cookie. </param>
        public virtual void CreateSessionCookie(
            IEnumerable<KeyValuePair<string, object>> user,
            string context = null,
            string domain = null,
            string path = null,
            bool requireSsl = false,
            bool httpOnly = true,
            string cookieName = null,
            TimeSpan? sessionCookieLifetime = null,
            bool persistent = false)
        {
            if (!string.IsNullOrEmpty(domain))
            {
                this.CookieHandler.Domain = domain;
            }

            if (!string.IsNullOrEmpty(path))
            {
                this.CookieHandler.Path = path;
            }

            if (!string.IsNullOrEmpty(cookieName))
            {
                this.CookieHandler.Name = cookieName;
            }

            this.CookieHandler.RequireSsl = requireSsl;
            this.CookieHandler.HideFromClientScript = httpOnly;

            var claims = new List<Claim>
                             {
                                 new Claim(ClaimTypes.Name, user.First(a => a.Key == "name").Value.ToString()),
                                 new Claim(
                                     ClaimTypes.NameIdentifier,
                                     user.First(a => a.Key == "user_id").Value.ToString()),
                                 new Claim(
                                     "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider",
                                     user.First(a => a.Key == "connection").Value.ToString())
                             };

            foreach (var attribute in user)
            {
                var claimType = attribute.Key;

                if (attribute.Value != null && attribute.Value.GetType().IsArray)
                {
                    // Attribute contains an array of values (e.g.: "group" => [ "sales", "producers" ])
                    foreach (var subattribute in attribute.Value as IEnumerable)
                    {
                        claims.Add(new Claim(claimType, subattribute.ToString()));
                    }
                }
                else
                {
                    claims.Add(
                        new Claim(claimType, attribute.Value != null ? attribute.Value.ToString() : string.Empty));
                }
            }

            var principal = new ClaimsPrincipal(new ClaimsIdentity[] { new ClaimsIdentity(claims, "Auth0") });

            this.OnBeforeCreateCookie(new BeforeCreateCookieEventArgs { Principal = principal });

            var session = this.CreateSessionSecurityToken(
                principal,
                context,
                DateTime.UtcNow,
                sessionCookieLifetime.HasValue
                    ? DateTime.UtcNow.Add(sessionCookieLifetime.Value)
                    : DateTime.MaxValue.ToUniversalTime(),
                persistent);
            this.AuthenticateSessionSecurityToken(session, true);
        }
 public static string GetUsername(this ClaimsPrincipal user)
 {
     // Name -> represents the unique name property
     return(user.FindFirst(ClaimTypes.Name)?.Value);
 }
Beispiel #39
0
 public UserApp(ClaimsPrincipal principal)
     : base(principal)
 {
 }
        /// <summary>
        /// Checks the authorization policy. Will throw a SecurityException when check fails.
        /// </summary>
        /// <param name="resource">The resource.</param>
        /// <param name="action">The action.</param>
        /// <param name="principal">The principal.</param>
        public static void DemandAccess(string resource, string action, ClaimsPrincipal principal)
        {
            Contract.Requires(!String.IsNullOrEmpty(resource));
            Contract.Requires(!String.IsNullOrEmpty(action));
            Contract.Requires(principal != null);

            
            if (!CheckAccess(resource, action, principal))
            {
                throw new SecurityException(string.Format("Demand for action: {0} for resource {1} failed", action, resource));
            }
        }
 public override void Authenticated(ClaimsPrincipal principal)
 {
     _context.User = principal;
     _tcs.TrySetResult(true);
 }
Beispiel #42
0
        public static IPrincipal GetOWinPrincipalUserFromCookiesValue(string cookiesValue, string authType)
        {
            IPrincipal user = null;

            cookiesValue = cookiesValue.Replace('-', '+').Replace('_', '/');

            var padding = 3 - ((cookiesValue.Length + 3) % 4);

            if (padding != 0)
            {
                cookiesValue = cookiesValue + new string('=', padding);
            }

            var bytes = Convert.FromBase64String(cookiesValue);

            bytes = System.Web.Security.MachineKey.Unprotect(bytes,
                                                             "Microsoft.Owin.Security.Cookies.CookieAuthenticationMiddleware",
                                                             authType, "v1");

            using (var memory = new MemoryStream(bytes))
            {
                using (var compression = new GZipStream(memory,
                                                        CompressionMode.Decompress))
                {
                    using (var reader = new BinaryReader(compression))
                    {
                        reader.ReadInt32();
                        string authenticationType = reader.ReadString();
                        reader.ReadString();
                        reader.ReadString();

                        int count = reader.ReadInt32();

                        var claims = new Claim[count];
                        for (int index = 0; index != count; ++index)
                        {
                            string type = reader.ReadString();
                            type = type == "\0" ? ClaimTypes.Name : type;

                            string value = reader.ReadString();

                            string valueType = reader.ReadString();
                            valueType = valueType == "\0" ?
                                        "http://www.w3.org/2001/XMLSchema#string" :
                                        valueType;

                            string issuer = reader.ReadString();
                            issuer = issuer == "\0" ? "LOCAL AUTHORITY" : issuer;

                            string originalIssuer = reader.ReadString();
                            originalIssuer = originalIssuer == "\0" ?
                                             issuer : originalIssuer;

                            claims[index] = new Claim(type, value,
                                                      valueType, issuer, originalIssuer);
                        }

                        var identity = new ClaimsIdentity(claims, authenticationType,
                                                          ClaimTypes.Name, ClaimTypes.Role);

                        user = new ClaimsPrincipal(identity);
                    }
                }
            }
            return(user);
        }
        public void UsersServiceMethodGetUserAuthenticationInfoShouldReturnTheAuthenticationInfoWithoutNameAndEmail()
        {
            // Arrange
            var claims = new[]
                                     {
                                         new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "WindowsLiveID") ,
                                         new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "user1")
                                     };

            IClaimsIdentity identity = new ClaimsIdentity(claims);
            IClaimsPrincipal principal = new ClaimsPrincipal(new[] { identity });
            var unitOfWorkMock = new Mock<IUnitOfWork>();
            var repository = new UsersMemoryRepository();
            var service = new UsersService(unitOfWorkMock.Object, repository);

            // Act
            var result = service.GetUserAuthenticationInfo(principal);

            // Assert
            Assert.IsNotNull(result);
        }
 public virtual ClaimsPrincipal Transform(string resource, ClaimsPrincipal incomingPrincipal)
 {
     if (Configuration.ClaimsAuthenticationManager != null)
     {
         return Configuration.ClaimsAuthenticationManager.Authenticate(resource, incomingPrincipal) as ClaimsPrincipal;
     }
     else
     {
         return incomingPrincipal;
     }
 }
        public void UsersServiceMethodIsRegisteredReturnsTrueForAnExistingUser()
        {
            // Arrange
            var claims = new[]
                                     {
                                         new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "WindowsLiveID") ,
                                         new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "user1"),
                                         new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", "*****@*****.**")
                                     };

            IClaimsIdentity identity = new ClaimsIdentity(claims);
            IClaimsPrincipal principal = new ClaimsPrincipal(new[] { identity });
            var unitOfWorkMock = new Mock<IUnitOfWork>();
            var repository = new UsersMemoryRepository();
            var service = new UsersService(unitOfWorkMock.Object, repository);

            // Act
            var result = service.UserIsRegistered(principal);

            // Assert
            Assert.IsTrue(result);
        }
        protected virtual ClaimsPrincipal InvokeHandler(SecurityTokenHandlerCollection handlers, string tokenString)
        {
            SecurityTokenHandler handler = null;

            if (handlers.Count == 1)
            {
                handler = handlers.First();
            }
            else
            {
                foreach (var h in handlers)
                {
                    if (((IHttpSecurityTokenHandler)h).CanReadToken(tokenString))
                    {
                        handler = h;
                        break;
                    }
                }
            }

            if (handler != null)
            {
                var token = ((IHttpSecurityTokenHandler)handler).ReadToken(tokenString);
                var principal = new ClaimsPrincipal(handler.ValidateToken(token));

                return principal;
            }

            throw new InvalidOperationException("No handler found");
        }
        protected virtual void SetPrincipal(ClaimsPrincipal principal)
        {
            if (principal.Identity.IsAuthenticated)
            {
                string name = "unknown";

                if (!string.IsNullOrWhiteSpace(principal.Identity.Name))
                {
                    name = principal.Identity.Name;
                }

                Tracing.Information(Area.HttpAuthentication, "Authentication successful for: " + name);
            }
            else
            {
                Tracing.Information(Area.HttpAuthentication, "Setting anonymous principal.");
            }

            Thread.CurrentPrincipal = principal;

            if (HttpContext.Current != null)
            {
                HttpContext.Current.User = principal;
            }
        }
Beispiel #48
0
 public static string RetriveEmailFromPrincipal(this ClaimsPrincipal user)
 {
     return(user?.Claims?.FirstOrDefault(x => x.Type == ClaimTypes.Email).Value);
 }
        public static int GetUserId(this ClaimsPrincipal user)
        {
            var userId = int.Parse(user.FindFirst(ClaimTypes.NameIdentifier)?.Value);

            return(userId);
        }
        public void UsersServiceMethodGFillUserAuthenticationInfoShouldFillTheAuthenticationInfo()
        {
            // Arrange
            var claims = new[]
                                     {
                                         new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "WindowsLiveID") ,
                                         new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "user1"),
                                         new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", "*****@*****.**"),
                                         new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "user1"),
                                     };

            IClaimsIdentity identity = new ClaimsIdentity(claims);
            IClaimsPrincipal principal = new ClaimsPrincipal(new[] { identity });
            var user = new User { Name = "user1" };
            var unitOfWorkMock = new Mock<IUnitOfWork>();
            var repository = new UsersMemoryRepository();
            var service = new UsersService(unitOfWorkMock.Object, repository);

            // Act
            service.FillAuthenticationInfo(user, principal);

            // Assert
            Assert.IsTrue(user.PartitionKey == "windowsliveid");
            Assert.IsTrue(user.RowKey == "user1-windowsliveid");
            Assert.IsTrue(user.UniqueIdentifier == "user1");
        }
 /// <summary>
 /// Creates a <see cref="TokenResponseReceivedContext"/>
 /// </summary>
 public TokenResponseReceivedContext(HttpContext context, AuthenticationScheme scheme, OpenIdConnectOptions options, ClaimsPrincipal user, AuthenticationProperties properties)
     : base(context, scheme, options, properties)
     => Principal = user;
        private Task<HttpResponseMessage> SendSessionTokenResponse(ClaimsPrincipal principal)
        {
            var token = _authN.CreateSessionToken(principal);
            var tokenResponse = _authN.CreateSessionTokenResponse(token);

            return Task<HttpResponseMessage>.Factory.StartNew(() =>
            {
                var response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StringContent(tokenResponse, Encoding.UTF8, "application/json");

                return response;
            });
        }
Beispiel #53
0
 public GlobalRouting(ClaimsPrincipal claimsPrincipal)
 {
     _claimsPrincipal = claimsPrincipal;
 }
        /// <inheritDoc/>
        public virtual LoginFormViewModel Authenticate(LoginFormViewModel input, HttpContextBase context)
        {
            User user;
            UserLoggingReason result = SecurityManager.AuthenticateUser(
                this.MembershipProvider,
                input.UserName,
                input.Password,
                input.RememberMe,
                out user);

            var identity = ClaimsManager.GetCurrentIdentity();
            if (user != null && identity != null && identity.OriginalIdentity is SitefinityIdentity)
            {
                IClaimsPrincipal cp = new ClaimsPrincipal(new[] { new ClaimsIdentity(identity.Claims) });
                var wifCredentials = new FederatedServiceCredentials(FederatedAuthentication.ServiceConfiguration);
                cp = wifCredentials.ClaimsAuthenticationManager.Authenticate(context.Request.RequestType, cp);
                SitefinityClaimsAuthenticationModule.Current.AuthenticatePrincipalWithCurrentToken(cp, input.RememberMe);
            }

            if (result == UserLoggingReason.Unknown)
            {
                input.IncorrectCredentials = true;
            }
            else
            {
                string redirectUrl;
                if (!this.TryResolveUrlFromUrlReferrer(context, out redirectUrl))
                {
                    redirectUrl = this.GetPageUrl(this.LoginRedirectPageId);
                }

                input.RedirectUrlAfterLogin = redirectUrl;

                if (result != UserLoggingReason.Success)
                {
                    SFClaimsAuthenticationManager.ProcessRejectedUser(context, input.RedirectUrlAfterLogin);
                }
            }

            return input;
        }
Beispiel #55
0
        private async Task <bool> ValidateSecurityStampAsync(UserManager <TUser> userManager, ClaimsPrincipal principal)
        {
            var user = await userManager.GetUserAsync(principal);

            if (user == null)
            {
                return(false);
            }
            else if (!userManager.SupportsUserSecurityStamp)
            {
                return(true);
            }
            else
            {
                var principalStamp = principal.FindFirstValue(_options.ClaimsIdentity.SecurityStampClaimType);
                var userStamp      = await userManager.GetSecurityStampAsync(user);

                return(principalStamp == userStamp);
            }
        }
        /// <summary>
        /// Executed when the authentication should be done.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The event args.</param>
        private void context_AuthenticateRequest(object sender, EventArgs e)
        {
            // Get the request.
            var request = ((HttpApplication)sender).Request;

            // The redirect back from the security token service is done using a POST method. Hence
            // abort processing of the current request, if it was not sent using POST.
            if (request.HttpMethod != "POST")
            {
                return;
            }

            // Check whether the request contains sign in data.
            if (request.Form["wa"] != WSFederationConstants.Actions.SignIn ||
                request.Form["wresult"].IsNullOrEmpty())
            {
                return;
            }

            // Otherwise, get the security token which is attached to the request, process it and
            // convert it to a principal. First, set up the federatec authentication module.
            var fam =
                new WSFederationAuthenticationModule
                    {
                        ServiceConfiguration =
                            new ServiceConfiguration
                                {
                                    AudienceRestriction = { AudienceMode = AudienceUriMode.Never },
                                    CertificateValidationMode =
                                        X509CertificateValidationMode.Custom,
                                    CertificateValidator = new CertificateValidator(c => true),
                                    IssuerNameRegistry = new X509CertificateIssuerNameRegistry()
                                }
                    };

            // Prepare the decryption by injecting the certificate to the service token resolver.
            var certificates =
                new List<SecurityToken>
                    {
                        new X509SecurityToken(
                            this.Container.Resolve<ICertificateManager>().GetEncryptingCertificate())
                    };
            var encryptedSecurityTokenHandler =
                (from handler in fam.ServiceConfiguration.SecurityTokenHandlers
                 where handler is EncryptedSecurityTokenHandler
                 select handler).First() as EncryptedSecurityTokenHandler;
            encryptedSecurityTokenHandler.Configuration.ServiceTokenResolver =
                SecurityTokenResolver.CreateDefaultSecurityTokenResolver(certificates.AsReadOnly(), false);

            // Get the security token from the request.
            var securityToken = fam.GetSecurityToken(request);

            // Validate the token and convert it to a collection of claims.
            var claims = fam.ServiceConfiguration.SecurityTokenHandlers.ValidateToken(securityToken);

            // Create a principal from the claims.
            IClaimsPrincipal principal = new ClaimsPrincipal(claims);

            // Set the current principal.
            HttpContext.Current.User = principal;
            Thread.CurrentPrincipal = principal;
        }
Beispiel #57
0
 //public FlightProfilesController(ATSEF_DBContext context, UserManager<AppUser> userManager, IHttpContextAccessor httpContextAccessor)
 public FlightProfilesController(ATSEF_DBContext context, IHttpContextAccessor httpContextAccessor)
 {
     _caller  = httpContextAccessor.HttpContext.User;
     _context = context;
 }
 private static AuthorizationContext CreateAuthorizationContext(ClaimsPrincipal currentPrincipal, ResourceAction resourceAction)
 {
     var resourceClaim = new Claim(resourceAction.ResourceType, resourceAction.Resource);
     var actionClaim = new Claim(resourceAction.ActionType, resourceAction.Action);
     
     return new AuthorizationContext(
         currentPrincipal, 
         new Collection<Claim> { resourceClaim }, 
         new Collection<Claim> { actionClaim });
 }
        public static ClaimsPrincipal Create()
        {
            var anonId = new ClaimsIdentity();
            var anonPrincipal = new ClaimsPrincipal(new ClaimsIdentityCollection(new ClaimsIdentity[]{anonId}));

            return anonPrincipal;
        }
        private static void SetPrincipal()
        {
            var idPclaims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, "Alice", ClaimValueTypes.String, "IdP"),
                new Claim(ClaimTypes.Email, "*****@*****.**", ClaimValueTypes.String, "IdP"),
                new Claim(ClaimTypes.Role, "Users", ClaimValueTypes.String, "IdP"),
                new Claim(ClaimTypes.Role, "Marketing", ClaimValueTypes.String, "IdP"),
                new Claim(ClaimTypes.Role, "Sales", ClaimValueTypes.String, "IdP"),
                new Claim("http://www.thinktecture.com/claims/location", "Heidelberg", ClaimValueTypes.String, "IdP")
            };

            var authZclaims = new List<Claim>
            {
                new Claim(WSAuthorizationConstants.Action, "AddCustomer", ClaimValueTypes.String, "RSTS"),
                new Claim(WSAuthorizationConstants.Action, "ChangeCustomer", ClaimValueTypes.String, "RSTS")
            };

            var idp = new ClaimsIdentity(idPclaims);
            var authZ = new ClaimsIdentity(authZclaims);

            var principal = new ClaimsPrincipal(new List<IClaimsIdentity> { idp, authZ });

            Thread.CurrentPrincipal = principal;
        }