gpt4 book ai didi

asp.net-mvc - 拒绝自定义角色

转载 作者:行者123 更新时间:2023-12-01 13:06:35 24 4
gpt4 key购买 nike

我怎样才能拒绝访问调用方法。像这样

    [HandleError]
[Authorize(Roles = "role1, role2")]
public class AdminController : Controller
{


[Deny(Roles = "role2")]
public ActionResult ResultPage(string message)
{
ViewData["message"] = message;
return View();
}
}

最佳答案

您可以简单地以相反的方式进行,检查角色 1 是否存在,而不是角色 2 是否存在。或者,您可以开发自己的 DenyAttribute 来执行您想要的操作并验证用户不在指定角色中。

[HandleError]
[Authorize(Roles = "role1, role2")]
public class AdminController : Controller
{


[Authorize(Roles = "role1")]
public ActionResult ResultPage(string message)
{
ViewData["message"] = message;
return View();
}
}

public class DenyAttribute : AuthorizeAttribute
{

protected override bool AuthorizeCore(HttpContextBase httpContext) {
if (httpContext == null) {
throw new ArgumentNullException("httpContext");
}

IPrincipal user = httpContext.User;
if (!user.Identity.IsAuthenticated) {
return false;
}

if (Users.Length > 0 && Users.Split(',').Any( u => string.Compare( u.Trim(), user.Identity.Name, StringComparer.OrdinalIgnoreCase))) {
return false;
}

if (Roles.Length > 0 && Roles.Split(',').Any( u => user.IsInRole(u.Trim()))) {
return false;
}

return true;
}

}

关于asp.net-mvc - 拒绝自定义角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2682545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com