Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Tom 713 posts 954 karma points
    May 27, 2011 @ 03:24
    Tom
    1

    Active Directory Membership/Roles Question

    Hi Guys,

    I have a scenario where I want to use active directory for front end membership.

    I'm struggling to get the back-office members section working.. and I'm wondering IS THERE AN EASIER APPROACH to the following:

    Based on a users role I will need to show or hide certain content portions:

    I have implemented the following in my web.config (projectname isn't real)

    <membership defaultProvider="CustomMembershipProvider" userIsOnlineTimeWindow="15">
        <providers>
            <clear />
            <add name="CustomMembershipProvider"
                     type="ProjectName.Web.CustomMembershipProvider"
                     connectionStringName="ADConnectionString"
                     connectionUsername="xxxx"
                     connectionPassword="xxxx"
                     connectionProtection="None"
                     attributeMapUsername="SAMAccountName" />
            <!--<add name="UmbracoMembershipProvider" type="umbraco.providers.members.UmbracoMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" defaultMemberTypeAlias="Another Type" passwordFormat="Hashed" />-->
            <add name="UsersMembershipProvider" type="umbraco.providers.UsersMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" passwordFormat="Hashed" />
        </providers>
    </membership>
    <!-- added by NH to support membership providers in access layer -->
    <roleManager enabled="true" defaultProvider="ProjectName_ActiveDirectoryRoleProvider">
        <providers>
            <clear />
            <add name="ProjectName_ActiveDirectoryRoleProvider" type="ProjectName.Web.CustomRoleProvider" />
        </providers>
    </roleManager>
    
    and then I have:
    public class CustomMembershipProvider : ActiveDirectoryMembershipProvider
        {
            public override MembershipUser GetUser(string username, bool userIsOnline)
            {
                return string.IsNullOrEmpty(username) ? null : base.GetUser(username, userIsOnline);
            }
        }

    and:

    public class CustomRoleProvider : RoleProvider
        {
            public override void AddUsersToRoles(string[] usernames, string[] roleNames)
            {
                throw new NotSupportedException();
            }
    
            public override string ApplicationName { get; set; }
    
            public override void CreateRole(string roleName)
            {
                throw new NotSupportedException();
            }
    
            public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
            {
                throw new NotSupportedException();
            }
    
            public override string[] FindUsersInRole(string roleName, string usernameToMatch)
            {
                throw new NotSupportedException();
            }
    
            public override string[] GetAllRoles()
            {
                throw new NotSupportedException();
            }
    
            public override string[] GetRolesForUser(string username)
            {
                string[] result;
                var tom = Roles.GetAllRoles();
                var identity = HttpContext.Current.User.Identity as FormsIdentity;
    
                if ((identity != null) && (identity.Name == username))
                {
                    result = identity.Ticket.UserData.Split(';');
                }
                else
                {
                    // check cache
    
                    using (var context = new PrincipalContext(ContextType.Domain, Settings.Default.MembershipDomain, Settings.Default.MembershipUsername, Settings.Default.MembershipPassword))
                    {
                        using (var principal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username))
                        using (var groups = principal.GetAuthorizationGroups())
                        {
                            result = groups.Select(group => group.SamAccountName).ToArray();
                        }
                    }
    
                    //HttpContext.Current.Cache.Add("RolesCache_" + username, result, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(30), CacheItemPriority.Normal, null);
                }
    
                return result;
            }
    
            public override string[] GetUsersInRole(string roleName)
            {
                throw new NotSupportedException();
            }
    
            public override bool IsUserInRole(string username, string roleName)
            {
                return GetRolesForUser(username).Contains(roleName);
            }
    
            public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
            {
                throw new NotSupportedException();
            }
    
            public override bool RoleExists(string roleName)
            {
                throw new NotSupportedException();
            }
        }

    It now appears my member's section in umbraco is somewhat broken.. when I try accessing the members section i just get the loading icon spinning..

    Ultimately what im trying to do is have a bunch of AD members who can log in.. I can then use standard membership and role calls to say Roles.UserIsInRole("Inductee") etc and show them content relevant to an induction..

    On member logged in we're dropping our own cookie which has a list of the AD groups for a given user for rapid comparison and if the member has a matching user name we authenticate them in the back-end.. 

    protected void MemberLogin_OnLoggedIn(object sender, System.EventArgs e)
            {
                var member = Membership.GetUser(MemberLogin.UserName);
    
                if (member != null)
                {
                    string roles = string.Join(";", Roles.GetRolesForUser(MemberLogin.UserName));
                    var cookie = Response.Cookies[FormsAuthentication.FormsCookieName];
                    var ticket = FormsAuthentication.Decrypt(cookie.Value);
                    ticket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, roles, ticket.CookiePath);
                    cookie.Value = FormsAuthentication.Encrypt(ticket);
    
                    if (Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].ValidateUser(member.UserName, MemberLogin.Password))
                    {
                        var cmsUser = new User(member.UserName);
                        if (cmsUser != null && cmsUser.Id > 0)
                        {
                            BasePage.doLogin(cmsUser);
    
                            // umbraco clears cookies, so we need to set this again
                            FormsAuthentication.SetAuthCookie(member.UserName, MemberLogin.RememberMeSet);
    
                            DeleteOldPreviews(cmsUser);
                        }
                        else
                        {
                            throw new InvalidOperationException("User not found: " + member.UserName);
                        }
                    }
                }
            }
Please Sign in or register to post replies

Write your reply to:

Draft