我有一个有效的登录系统,需要用户进行身份验证。问题是我不知道如何将[Authorize]属性中指定的角色连接到我的数据库中指定的角色。
我希望有人可以帮助我,因为我不知道从哪里开始,也无法在互联网上找到任何有用的东西。
这是我的帐户控制器:
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();
}
}
}
我的授权设置如下:
[Authorize]
public class AdminController : Controller
{
[Authorize(Roles = "Admin")]
public ViewResult Index()
{
return View();
}
我制作了一个自定义的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;
}
}
这是我的用户类:
public class User
{
[Key]
public string Username { get; set; }
public string Password { get; set; }
public string Role { get; set; }
}
答案 0 :(得分:1)
如果要将自定义表用于角色,则应实现角色提供程序。您可以通过继承自 System.Web.ApplicationServices.dll 中的抽象基类 System.Web.Security.RoleProvider 来实现此目的。从 RoleProvider 继承后,您可能会被自动创建的所有方法吓倒。您只需提供将要使用的方法的实现(在您的情况下,我认为它将是 GetRolesForUser )。
实施角色提供程序后,使用 web.config 在框架中注册。
如果您不熟悉整个成员资格提供程序模式,请查看以下文章。 http://www.mattwrock.com/post/2009/10/14/implementing-custom-membership-provider-and-role-provider-for-authinticating-aspnet-mvc-applications.aspx
干杯