【发布时间】:2014-04-30 20:05:46
【问题描述】:
我有一个有效的登录系统,需要用户进行身份验证。问题是我不知道如何将 [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; }
}
【问题讨论】: