Friday, April 18, 2008

Intranet Applications with Role-based Security using Windows Authentication and SQL Server

First of all, I would like to thank ScottGu, again for a job well done on this tutorial on how to implement Windows authentication for an INTRANET website that works against a sql server database.

I recently added authentication scheme for an intranet website that I developed. There are some reports and tools that are supposed to be accessed only by some priviledged people within the organization. No login is required since this is an intranet application. But I needed a way to restrict access to some pages. The easiest way to maintain such a website is by adding a role-based security that is tied-in to Active Directory user account. Anyways, following this recipe that Scott Gu concocted, I got up and running quickly. Thank you Scott!

Btw, I translated the Visual Basic code to C# below...

private void PopulateRoleList(string userName)

    {

        if (!String.IsNullOrEmpty(userName))

        {

            RoleList.Items.Clear();

            foreach (string roleName in Roles.GetAllRoles())

            {

                ListItem roleListItem = new ListItem();

                roleListItem.Text = roleName;

                roleListItem.Selected = Roles.IsUserInRole(userName, roleName);

                RoleList.Items.Add(roleListItem);

            }

        }

    }

 

    private void UpdateRolesFromList()

    {

        foreach (ListItem roleListItem in RoleList.Items)

        {

            string roleName = roleListItem.Value;

            string userName = TxtUserName.Text;

            bool enableRole = roleListItem.Selected;

 

            if (enableRole == true && Roles.IsUserInRole(userName, roleName) == false)

            {

                Roles.AddUsersToRole(new string[] { userName }, roleName);

            }

            else if (enableRole == true && Roles.IsUserInRole(userName, roleName) == true)

            {

                Roles.RemoveUserFromRole(userName, roleName);

            }

        }

    }

 

    protected void LookupBtn_Click(object sender, EventArgs e)

    {

        PopulateRoleList(TxtUserName.Text);

        UpdateBtn.Visible = true;

        LabelRoleMembership.Visible = true;

    }

 

    protected void UpdateBtn_Click(object sender, EventArgs e)

    {

        UpdateRolesFromList();

        PopulateRoleList(TxtUserName.Text);

        PopulateRoleList(TxtUserName.Text);

    }

0 comments: