【问题标题】:Creating a custom Authorize attribute with specific rules使用特定规则创建自定义 Authorize 属性
【发布时间】:2016-10-28 17:58:58
【问题描述】:

我正在尝试创建一个自定义 Authorize 属性来执行以下操作:

  1. 如果用户具有“普通用户”角色 - 他将被重定向到 /index/subscribe
  2. 所有其他用户(管理员、订阅者)都可以访问 /Search/Index

这是用户尝试打开搜索控制器的时候。我制作了这样的自定义 Authorize 属性:

public class DenyRegularUser : System.Web.Mvc.AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult("~/User/Logon");
                return;
            }

            if (filterContext.HttpContext.User.IsInRole("Regular user"))
            {
                filterContext.Result = new RedirectResult("~/Index/Subscribe");
            }
        }
    }

这是我的搜索控制器:

namespace WebApplication2.Controllers
{
    [DenyRegularUser(Roles ="Regular user")]
    public class SearchController : Controller
    {
        // GET: Search
        public ActionResult Index()
        {
            return View();
        }
    }
}

但由于某种原因,即使我将用户角色从普通用户更新为管理员或订阅者,我也会被重定向到登录页面:/user/login...

这不应该发生,因为登录功能可以完美运行并且我获得了用户的角​​色...

我在这里错过了什么??

【问题讨论】:

  • 您尝试的“Admin”/“Subscriber”用户是否也属于“Regular user”组?

标签: c# asp.net asp.net-mvc c#-4.0 authorize


【解决方案1】:

这可能会有所帮助。

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class DenyRegularUser  : AuthorizeAttribute
{
    public DenyRegularUser() :
        base()
    {

    }

    protected override bool IsAuthorized (System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if (AuthorizeRequest(actionContext))
        {
            return true;
        }
        return false;
    }

    protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        //Code to handle unauthorized request
        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.TemporaryRedirect);
        actionContext.Response.Headers.Add("Location", "~/Index/Subscribe");
    }

    private bool AuthorizeRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        //Write your code here to perform authorization
    }
}

我相信 IsAuthorized 方法是覆盖 AuthorizeAttribute 的正确方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    相关资源
    最近更新 更多