1

我需要最好的方法来进行基于角色的菜单导航。我的应用程序在 Asp.net core MVC 中,并且我使用了基于 cookie 的身份验证。我正在使用声明身份。

4

1 回答 1

0

如果您对 asp.net 核心使用 cookie 身份验证,这意味着您需要在每个请求上验证用户角色。根据您认为在 cookie 中定义的角色,您会显示某些内容。以下是创建 cookie 的方法:

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                        1, //ticket version
                        person.username,
                        DateTime.Now,
                        DateTime.Now.Add(new TimeSpan(2, 0, 0)),
                        true, //persistent cookies
                        "Administrator",// <---ROLES // 
                        FormsAuthentication.FormsCookiePath
                    );


string hashedTicket = FormsAuthentication.Encrypt(ticket);

HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashedTicket);

HttpContext.Response.Cookies.Add(cookie);

return RedirectToLocal(returnUrl);

将其添加到您的登录/注册机制

然后在你的 global.asax 中你应该有以下方法:

protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        // look if any security information exists for this request
        if (HttpContext.Current.User != null)
        {
            // see if this user is authenticated, any authenticated cookie (ticket) exists for this user
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                // see if the authentication is done using FormsAuthentication
                if (HttpContext.Current.User.Identity is FormsIdentity)
                {
                    // Get the roles stored for this request from the ticket
                    // get the identity of the user
                    FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;
                    //Get the form authentication ticket of the user
                    FormsAuthenticationTicket ticket = identity.Ticket;
                    //Get the roles stored as UserData into ticket
                    string[] roles = { ticket.UserData };


                    //Create general prrincipal and assign it to current request

                    HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);
                }
            }
        }
    }

然后,当您想向管理员显示某些 html 时,在您的视图中添加以下内容:

@if (User.IsInRole("Administrator"))
{
     <li>
         <a href="@Url.Action("Index","Main",new { Area = "Admin" })">Admin</a>
     </li>
     <li>
         <a href="#" onclick="showpencil()">Edit</a>
     </li>
}

小更新 如果您想过滤控制器中的访问权限,只需添加:

[Authorize(Roles = "Administrator")] 

如果您想限制所有方法,则在类级别上,或者如果您只想限制该方法,则将其添加到单个方法之上。

于 2019-11-19T11:40:21.343 回答