Quantcast
Channel: Security
Viewing all articles
Browse latest Browse all 4737

Mixed mode authentication with windows and custom Claims

$
0
0

I have an asp.net MVC application using windows authentication from SQL Server database which works fine. Now I want to add Claims based authentication using Custom STS. When a user click on the application url it will check if the person has windows account and verify it against Roles and permissions in SQL Sever database then authenticate the person. If the Person doesn't have Windows account, they should be Redirected to the Custom STS Page where their email will be verify, take the token and verify it against SQL Server database to see if the email is associated with the Roles and Permission in the database. I can't seem to get this working. Below is my code. Any help will be appreciated.

 public class User
    {
        public int User_Id { get; set; }
        public bool IsSysAdmin { get; set; }
        public string Username { get; set; }
        public string userEmail { get; set; }
        private readonly List<UserRole> Roles = new List<UserRole>();
        readonly List<Claim> cls = new List<Claim>();

        public CDRLUser(string _username, string _usermail)
        {
            Username = _username;
            userEmail = _usermail;
            IsSysAdmin = false;
            GetDatabaseUserRolesPermissions();
        }

        private void GetDatabaseUserRolesPermissions()
        {
            using (var _data = new Model())
            {
                if (Username != null)
                {
                    _data.Configuration.LazyLoadingEnabled = false;
                    var _user = _data.USERS.FirstOrDefault(u => u.Username == Username);
                    _data.Entry(_user).Collection(u => u.ROLES).Load();
                    if (_user != null)
                    {
                        User_Id = _user.User_Id;
                        foreach (var _role in _user.ROLES)
                        {
                            var _userRole = new UserRole
                            {
                                Role_Id = _role.Role_Id,
                                RoleName = _role.RoleName,
                                RoleDescription = _role.RoleDescription
                            };
                            foreach (var _permission in _role.PERMISSIONS)
                            {
                                _userRole.Permissions.Add(new PERMISSION
                                {
                                    Permission_Id = _permission.Permission_Id,
                                    PermissionDescription = _permission.PermissionDescription,
                                    ROLES = _permission.ROLES
                                });
                            }
                            Roles.Add(_userRole);
                            if (!IsSysAdmin)
                                IsSysAdmin = _role.IsSysAdmin;
                        }
                    }
                }
                else if (userEmail != null)
                {
                    {
                        _data.Configuration.LazyLoadingEnabled = false;
                        var _email = _data.USERS.FirstOrDefault(t => t.Identifier == userEmail);
                         if (_email != null)
                         {
                             var cl = new Claim(ClaimTypes.Email, _email.Identifier);
                            cls.Add(cl);
                        }
                        _data.Entry(_email).Collection(t => t.ROLES).Load();
                       if (_email != null)
                        {
                            User_Id = _email.User_Id;
                            foreach (var _role2 in _email.ROLES)
                            {
                                var _userRole2 = new UserRole
                                {
                                    Role_Id = _role2.Role_Id,
                                    RoleName = _role2.RoleName,
                                    RoleDescription = _role2.RoleDescription
                                };
                                foreach (var _permission in _role2.PERMISSIONS)
                                {
                                    _userRole2.Permissions.Add(new PERMISSION
                                    {
                                        Permission_Id = _permission.Permission_Id,
                                        PermissionDescription = _permission.PermissionDescription,
                                        ROLES = _permission.ROLES
                                    });
                                }
                                Roles.Add(_userRole2);

                                if (!IsSysAdmin)
                                    IsSysAdmin = _role2.IsSysAdmin;
                            }
                        }
                    }

                }
             }
        }


        public bool HasPermission(string requiredPermission)
        {
            var bFound = false;
            foreach (var role in Roles)
            {
                bFound =
                    (role.Permissions.Where(p => String.Equals(p.PermissionDescription, requiredPermission, StringComparison.CurrentCultureIgnoreCase))
                        .ToList()
                        .Count > 0);
                if (bFound)
                    break;
            }
            return bFound;
        }

        public bool HasRole(string role)
        {
            return (Roles.Where(p => p.RoleName == role).ToList().Count > 0);
        }

        
        public bool HasRoles(string roles)
        {
            var bFound = false;
            var _roles = roles.ToLower().Split(';');
            foreach (var role in Roles)
            {
                try
                {
                    bFound = _roles.Contains(role.RoleName.ToLower());
                    if (bFound)
                        return true;
                }
                catch (Exception ex)
                {
                    DataProvider.PresenterLayerException(ex);
                    ControllerUnHandledExp.LogError(ex);
                }
            }
            return bFound;
        }


 
        public class UserRole
        {
            public int Role_Id { get; set; }
            public string RoleName { get; set; }
            public string RoleDescription { get; set; }
            public bool IsSysAdmin { get; set; }
            public DateTime? LastModified { get; set; }
            public List<PERMISSION> Permissions = new List<PERMISSION>();

        }
    }
}



*************************************************************************************************************************

    protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext.User.Identity.IsAuthenticated && httpContext.User.Identity.AuthenticationType.Equals(WIF.AuthenticationTypes.Federation, StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }

            return false;
        }
        
           public override void OnAuthorization(AuthorizationContext filterContext)
        {
             var requiredPermission = String.Format("{0}-{1}", filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,                   filterContext.ActionDescriptor.ActionName);
             var requestingUser = new MyUser(filterContext.RequestContext.HttpContext.User.Identity.Name);
             if (!requestingUser.HasPermission(requiredPermission) & !requestingUser.IsSysAdmin)
             {
                 HandleUnauthorizedRequest(filterContext);
            }
             else
             {
                 //User doesn't have the required permission and is not a SysAdmin, return our custom “401 Unauthorized” access error
                 filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "action", "Index" }, { "controller", "Unauthorised" } });
             }
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            // do the redirect to the STS
            var message = FederatedAuthentication.WSFederationAuthenticationModule.CreateSignInRequest("passive", filterContext.HttpContext.Request.RawUrl, false);
            filterContext.Result = new RedirectResult(message.RequestUrl);
        }

    }
}


Viewing all articles
Browse latest Browse all 4737

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>