Reputation: 13
I have a working login system, that required users to authenticate. The problem is I don't know how to connect the roles specified in the [Authorize] attribute to the roles specified in my database.
I hope someone can help me, because I don't really know where to start and can't find anything useful on the internet.
This is my accountcontroller:
public class AccountController : Controller
{
IAuthProvider authProvider;
public AccountController(IAuthProvider auth) {
authProvider = auth;
}
public ViewResult Login() {
return View();
}
[HttpPost]
public ActionResult Login(LoginViewModel model, string returnUrl) {
if (ModelState.IsValid) {
if (authProvider.Authenticate(model.Gebruikersnaam, model.Wachtwoord)) {
return Redirect(returnUrl ?? Url.Action("Index", "Admin"));
} else {
ModelState.AddModelError("", "Foute gebruikersnaam of wachtwoord");
return View();
}
} else {
return View();
}
}
}
I have my authorization set up like so:
[Authorize]
public class AdminController : Controller
{
[Authorize(Roles = "Admin")]
public ViewResult Index()
{
return View();
}
I made a custom AuthProvider:
public class FormsAuthProvider : IAuthProvider
{
IUserRepository repository { get; set; }
public FormsAuthProvider(IUserRepository repo)
{
repository = repo;
}
public bool Authenticate(string username, string password)
{
bool result = false;
IEnumerable<User> users = repository.GetAllUsers();
if (users.Any(g => g.Username == username && g.Password == password)) {
result = true;
}
if (result) {
FormsAuthentication.SetAuthCookie(username, false);
}
return result;
}
}
This is my user class:
public class User
{
[Key]
public string Username { get; set; }
public string Password { get; set; }
public string Role { get; set; }
}
Upvotes: 0
Views: 67
Reputation: 1820
If you are to use your custom tables for roles, you should implement a roles provider. You can do this by inheriting from abstract base class System.Web.Security.RoleProvider which lives in System.Web.ApplicationServices.dll. Once you inherit from RoleProvider you may be intimidated by all the methods automatically created. You will only have to provide implementations for methods you will be using (in your case I think it would be GetRolesForUser).
Once you implement the roles provider, register it with the framework using the web.config.
Have a look at the following article if you are new to the whole membership provider pattern. http://www.mattwrock.com/post/2009/10/14/implementing-custom-membership-provider-and-role-provider-for-authinticating-aspnet-mvc-applications.aspx
Cheers
Upvotes: 1