asp.net-mvc HttpContext.Current.User.IsInRole 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8984085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:42:19  来源:igfitidea点击:

HttpContext.Current.User.IsInRole not working

asp.net-mvcsecurity

提问by Old Geezer

in my controller AuthController/signin i have this code:

在我的控制器 AuthController/signin 我有这个代码:

    entities.UserAccount user = (new BLL.GestionUserAccount()).authentifier(email, password);
            //storing the userId in a cookie
            string roles = (new BLL.GestionUserAccount()).GetUserRoles(user.IdUser);
            // Initialize FormsAuthentication, for what it's worth

            FormsAuthentication.Initialize();

            //

            FormsAuthentication.SetAuthCookie(user.IdUser.ToString(), false);

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
            1, // Ticket version
            user.IdUser.ToString(), // Username associated with ticket
            DateTime.Now, // Date/time issued
            DateTime.Now.AddMinutes(30), // Date/time to expire
            true, // "true" for a persistent user cookie
            roles, // User-data, in this case the roles
            FormsAuthentication.FormsCookiePath);// Path cookie valid for

            // Encrypt the cookie using the machine key for secure transport
            string hash = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(
               FormsAuthentication.FormsCookieName, // Name of auth cookie
               hash); // Hashed ticket



                // Get the stored user-data, in this case, our roles

            // Set the cookie's expiration time to the tickets expiration time
            if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;

            // Add the cookie to the list for outgoing response
            Response.Cookies.Add(cookie);
            return RedirectToAction("index", "Home");

in the master page i have a menu ,in that menu there is an item that is meant to be seen only by admin role.

在母版页中,我有一个菜单,在该菜单中有一个只能由管理员角色看到的项目。

     <% if (HttpContext.Current.User.IsInRole("admin")){ %>

            <%=Html.ActionLink("Places", "Places", "Places")%>
        <%} %>

even with HttpContext.Current.User conatining the right roles,i can't see the item:

即使 HttpContext.Current.User 包含正确的角色,我也看不到该项目:

enter image description here

在此处输入图片说明

globalx asax:

globalx asax:

    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        if (HttpContext.Current.User != null)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (HttpContext.Current.User.Identity is FormsIdentity)
                {
                    FormsIdentity id =
                        (FormsIdentity)HttpContext.Current.User.Identity;
                    FormsAuthenticationTicket ticket = id.Ticket;

                    // Get the stored user-data, in this case, our roles
                    string userData = ticket.UserData;
                    string[] roles = userData.Split(',');
                    HttpContext.Current.User = new GenericPrincipal(id, roles);
                }
            }
        }
    }

采纳答案by gideon

I know it sounds silly but from your image I can only see your userDatafrom your ticket.

我知道这听起来很傻,但从你的图片中我只能userData从你的票中看到你。

The only thing I can think if is if the userDatais not going into the principal. (Possibly a problem with the last three lines of glabal.asax.cs)

我唯一能想到的是,如果userData不进入校长。(可能是glabal.asax.cs的最后三行有问题)

Something is wrong here:

这里不对劲:

string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new GenericPrincipal(id, roles);

回答by Old Geezer

Instead of using User.IsInRole(), try the static method Roles.IsUserInRole().

而不是使用User.IsInRole(),尝试静态方法Roles.IsUserInRole()

回答by Darin Dimitrov

You will need a custom Authorize attribute which will parse the user data portion of the authentication ticket and manually create the IPrincipal. Take a look at this postwhich illustrates the way I would recommend you to do this in ASP.NET MVC. Never use HttpContext.Currentin an ASP.NET MVC application. Not even in your views. Use <% if (User.IsInRole("admin")) { %>instead.

您将需要一个自定义 Authorize 属性,该属性将解析身份验证票的用户数据部分并手动创建 IPrincipal。看看这篇文章,它说明了我建议您在 ASP.NET MVC 中执行此操作的方式。切勿HttpContext.Current在 ASP.NET MVC 应用程序中使用。甚至在你看来也不行。使用<% if (User.IsInRole("admin")) { %>来代替。

回答by Jeff Lim

One statement is missing.

缺少一项声明。

After this line:

在这一行之后:

FormsAuthenticationTicket ticket = id.Ticket;

You need to put this line:

你需要把这一行:

ticket = FormsAuthentication.Decrypt(ticket.Name);

回答by Sebastian Xawery Wi?niowiecki

In global.asax assign principal on 2 objects like that:

在 global.asax 中为 2 个对象分配主体,如下所示:

    private static void SetPrincipal(IPrincipal principal)
    {
        Thread.CurrentPrincipal = principal;
        if (HttpContext.Current != null)
        {
            HttpContext.Current.User = principal;
        }
    }

I found it here ASP.NET documentation

我在这里找到了ASP.NET 文档