【问题标题】:How to specify user roles如何指定用户角色
【发布时间】: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; }
}

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    如果您要将自定义表用于角色,则应实施角色提供程序。您可以通过继承抽象基类 System.Web.Security.RoleProvider 来做到这一点,它位于 System.Web.ApplicationServices.dll 中。一旦您从 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

    干杯

    【讨论】:

      猜你喜欢
      • 2020-02-12
      • 2018-11-25
      • 2020-11-20
      • 2012-06-02
      • 2014-01-31
      • 1970-01-01
      • 2016-11-28
      • 2023-01-04
      • 2017-12-04
      相关资源
      最近更新 更多