【问题标题】:Roles based Authentication is not working using asp.net mvc4基于角色的身份验证无法使用 asp.net mvc4
【发布时间】:2014-01-28 10:37:11
【问题描述】:
<authorization>
  <allow roles = "Admin" />
  <deny users="?"/>
</authorization>

角色已分配

 protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
    {
        if (FormsAuthentication.CookiesSupported == true)
        {
            if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
            {      
                string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                string roles = string.Empty;
                bool check;
                using (RealEstateEntities db = new RealEstateEntities())
                {
                    check = db.Admins.Any(model => model.Roles == "Admin" && model.UserName == username);
                }
                if (check)
                    roles = "Admin";
                else
                    roles = "User";
               //  GenericPrincipal userPrincipal = new GenericPrincipal(new GenericIdentity(username,"Forms"), roles);
                Context.User = new GenericPrincipal(new GenericIdentity(username, "Forms"), roles.Split(';'));
            }
        }
    }

Global.asax

[Authorize(Roles = "Admin")]

*但它不起作用*

[Authorize(Users = "Abid")]

当我在网络配置中将角色更改为用户时它可以工作 我是 mvc4 的新手,请帮忙!

【问题讨论】:

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


    【解决方案1】:

    在 asp.net MVC 4 中,您不应在 web.config 文件中使用授权(除非您想保护自定义文件夹)。

    你应该注册一个全局过滤器:

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new System.Web.Mvc.AuthorizeAttribute());
    }
    

    当您不希望对您的操作进行任何形式的授权时,请使用 AllowAnonymous

    您可以在hereherehere找到详细解释。

    这个article 向您展示了不同asp.net 版本之间的差异。

    希望对你有帮助。

    【讨论】:

    • “你不应该在你的 web.config 文件中使用授权” - 这如何与 Content 文件夹中的静态内容一起工作?
    • 好点。如果您使用捆绑,则不必使用 web.config,否则您是对的,您必须使用它。
    猜你喜欢
    • 2016-03-07
    • 2018-09-06
    • 2013-08-23
    • 2016-01-03
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    相关资源
    最近更新 更多