ASP.NET, like any other web development system, has a “role provider” system to handle authorization. With a small quantity of code, you can hook your custom security settings into this API and get authorization essentially for “free”. Not every organization uses it, because it’s not sufficient for every security situation, but it’s a good starting point, and it’s guaranteed that it’ll be covered in any ASP.NET training course.

Paul’s employer recently found a new hiring strategy. Instead of hiring expensive, well qualified people, they hire completely inexperienced people on the cheap, and send them to training classes. That’s likely where this code started its life- cribbed from notes in a training class.

private void AddUserToRole(List<NewAlumUser> users, int r)
{
        if (!Roles.RoleExists("Level" + users[r].Accesslevel))
        {
                Roles.CreateRole("Level" + users[r].Accesslevel);
        }

//checks if they are in the role... GOOD
        if (!(Roles.IsUserInRole(users[r].User_name, "Level" + users[r].Accesslevel)))
        {
                string[] rolesforuser = Roles.GetRolesForUser(users[r].User_name);
                string[] userroles = Roles.GetUsersInRole("Level" + users[r].Accesslevel);
                int count = rolesforuser.GetUpperBound(0);
                string currentrole = "";

                for (int i = 0; i <= count; i++)
                {
                        currentrole = rolesforuser[i].ToUpper() + currentrole;
                }
                if (!(currentrole.Contains("LEVEL" + users[r].Accesslevel.ToUpper())))
                {
                        try
                        {
                                Roles.AddUserToRole(users[r].User_name, "Level" + users[r].Accesslevel);
                        }
                        catch (Exception ex)
                        {
                                createfile("AddUserToRole", users[r].User_name + "\r\n" + users[r].Accesslevel + "\r\n" + ex.Message + "\r\n" + ex.Source + "\r\n" + ex.StackTrace);
                        }
                }
        }

        //if (Roles.IsUserInRole(users[r].User_name.ToLower()) == false && Roles.IsUserInRole(users[r].User_name.ToUpper()) == false)
}

Now, there are a few obvious problems with this code. The for loop in the middle is an incredibly special snowflake. Beyond that, this code is in-line in the code-behind for a SharePoint page , and is called every time the page is rendered.

The real kicker, though, is that Paul’s organization uses a custom membership provider that doesn’t implement RoleExists, meaning this code just throws an exception every time it’s called anyway.

[Advertisement] Scale your release pipelines, creating secure, reliable, reusable deployments with one click. Download and learn more today!