How do I manually set a user's role in ASP.NET MVC?

Colin O'Dell picture Colin O'Dell · Aug 19, 2009 · Viewed 22.5k times · Source

This project I'm working on requires me to keep a local db of admin users and use an external db for regular users. Anyone who passes authentication in the admin db should be assigned the 'admin' role, and anyone authenticated through the other db will always be assigned a 'user' role.

Can I manually assign these roles? I don't need the complexity of a Role Provider or anything, since I'm only using these two roles which will ALWAYS be based on which db they authenticate with.

It would be a HUGE help if you could provide sample code or a link to some documentation. Thanks!

EDIT:

Currently I am not using the role provider and creating one seems like a hassle. I know its not 'best-practice', but I only need to assign 1 of 2 roles during login (this will never change). It also doesn't make sense to store role information in the database, since users are already separated into 2 dbs by their role.

Here's some pseudo-code:

if (AdminDB.ValidateUser(username,password)==true) {
     SetAuthCookie(username);
     AssociateUserWithRole(username, 'admin');
} elseif (UserDB.ValidateUser(username,password)==true) {
     SetAuthCookie(username);
     AssociateUserWithRole(username, 'user');
} else {
     // Login failed.
}

Its the 'ThisSession.AssociateUserWithRole' part I don't know. Basically, one the user is authenticated, I need to tell .NET which role the user belongs to.

Answer

tvanfosson picture tvanfosson · Aug 19, 2009

Implementing a role provider is not particularly hard -- especially if you are only implementing the role checking, not the role management. Just implement those portions that you need and have the rest throw NotImplementedExceptions. If you only have one application you need not be too concerned about that portion either. Note that the portions that you need will be dictated by how the framework uses it, not how you would use it. I think for example you will need to implement the bit that returns all the user's roles even if you only want to check if they are in a specific role.

That said, you could omit the whole RoleProvider and do the whole thing in the Session. In this case you'd implement your own AuthorizeAttribute and replace it's authentication and role-checking bits with your own. Store the user's role in the session once authenticated and check it there using your attribute and the parameters supplied to the attribute for the method/class you've decorated it with.