I had the same requirement. I had my own user and role scheme, and I did not want to migrate to asp.net membership scheme, but I wanted to use ASP.NET MVC action filters to check permissions and roles. I had to do quite a lot of digging to find out what exactly needs to be done, but in the end it was relatively easy. I will save you trouble and tell you what I did.
1) I created a class derived from System.Web.Security.MembershipProvider. MembershipProvider has a ton of abstract methods for all kinds of authentication related functions, such as a forgotten password, password change, creating a new user, etc. All I wanted was the ability to authenticate against my own scheme. Therefore, my class contained mostly empty overrides. I just overridden ValidateUser:
public override bool ValidateUser(string username, string password) { if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password)) return false; string hash = EncryptPassword(password); User user = _repository.GetByUserName(username); if (user == null) return false; return user.Password == hash; }
2) I created a class derived from System.Web.Security.RoleProvider. Again, I just had empty implementations for all the fluff that I don't need, like creating and changing roles. I just redefined two methods:
public override string[] GetRolesForUser(string username) { User user = _repository.GetByUserName(username); string[] roles = new string[user.Role.Rights.Count + 1]; roles[0] = user.Role.Description; int idx = 0; foreach (Right right in user.Role.Rights) roles[++idx] = right.Description; return roles; } public override bool IsUserInRole(string username, string roleName) { User user = _repository.GetByUserName(username); if(user!=null) return user.IsInRole(roleName); else return false; }
3) Then I included these two classes in my web.config:
<membership defaultProvider="FirstlookMemberProvider" userIsOnlineTimeWindow="15"> <providers> <clear/> <add name="FirstlookMemberProvider" type="FirstlookAdmin.DomainEntities.FirstlookMemberProvider, FirstlookAdmin" /> </providers> </membership> <roleManager defaultProvider="FirstlookRoleProvider" enabled="true" cacheRolesInCookie="true"> <providers> <clear/> <add name="FirstlookRoleProvider" type="FirstlookAdmin.DomainEntities.FirstlookRoleProvider, FirstlookAdmin" /> </providers> </roleManager>
What is it. The default action filters will use these classes. You still have to process the login and sign up. Just use standard authentication classes for this, as usual.
Matt Wrock Sep 17 '09 at 14:44 2009-09-17 14:44
source share