Windows Authentication and add Authorization Roles through database – MVC asp.net

You just need to create a custom role provider. You do this by creating a class that inherits from System.Web.Security.RoleProvider and overriding certain members. The below code should get you started. Replace all the throw new NotImplementedException() stuff with your implementation of the function. For example, IsUserInRole you would provide code that would query your database to see if the user is in the specified role.

using System.Web.Security;

namespace MyNamespace
{        
    public class MyRoleProvider : RoleProvider
    {
        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override string ApplicationName
        {
           get; set;
        }

        public override void CreateRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            throw new NotImplementedException();
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            throw new NotImplementedException();
        }

        public override string[] GetAllRoles()
        {
            throw new NotImplementedException();
        }

        public override string[] GetRolesForUser(string username)
        {
            throw new NotImplementedException();
        }

        public override string[] GetUsersInRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool IsUserInRole(string username, string roleName)
        {
            throw new NotImplementedException();
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override bool RoleExists(string roleName)
        {
            throw new NotImplementedException();
        }
    }
}

You may not need to implement all of it. For example, if your application won’t be creating or deleting Roles, then no need to do anything with CreateRole or DeleteRole.

You also need to register your role provider with ASP.NET framework so it knows to make use of it. Update your web.config like below.

<configuration>
    <system.web>
        <roleManager defaultProvider="MyRoleProvider" enabled="true">
            <providers>
                <add
                    name="MyRoleProvider"
                    type="MyNamespace.MyRoleProvider"           
                    applicationName="MyApplicationName" />
            </providers>
        </roleManager>
    </system.web>
</configuration>

Leave a Comment