How can I implement my own RoleProvider?

I am trying to implement a custom RoleProvider in my ASP.NET MVC application.

I created a custom MemberhipProvider and it works because I can verify the user successfully. The next step would be to implement a RoleProvider to restrict access to controllers only for Admin users.

Can anyone provide me with a short description of the steps I need to take?

What I am currently finding is my controller with an authorization filter like:

[Authorize(Roles="Admin")]
public class AdminOnlyController : Controller
{ 
    // stuff 
}

      

and I have my CustomRoleProvider class with the following method along with loading unimplemented methods:

public override string[] GetRolesForUser(string username)
{
    if (username == "dave")
    {
        return new string[] { "Admin" };
    }
}

      

I think I need to add the user to the role somehow, but I don't know how. Ideally, the end result would be a scenario where unauthorized users cannot access certain controllers, and I can determine in my views whether to show links with something like:

if (User.IsInRole("Admin"))
{
    // show links to Admin Controllers
}

      

Can anyone point me in the right direction?

+2


source to share


2 answers


I used this as a baseline for a custom role manager: http://davidhayden.com/blog/dave/archive/2007/10/17/CreateCustomRoleProviderASPNETRolePermissionsSecurity.aspx

Should work in MVC or web forms.



UPDATE. Since this webpage no longer exists, you can try this one instead . The basic requirements are that you need to implement the RoleProvider interface, namely:

void AddUsersToRoles(string[] usernames, string[] roleNames)
string[] GetRolesForUser(string id)
bool RoleExists(string roleName)

      

+3


source


For methods not implemented, be sure to throw a NotImplementedException . This will help you figure out what methods are needed in your custom provider to get the job done.



I suspect you will have to implement IsUserInRole .

+2


source







All Articles