我需要最好的方法来进行基于角色的菜单导航。我的应用程序是Asp.net核心MVC,我使用了基于cookie的身份验证。我正在使用索赔身份。
如果您对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")]
如果您想限制所有方法,则在类级别上;如果您想仅限制该方法,则将其添加到单个方法之上。