[英]Creating a custom Authorize attribute with specific rules
I'm trying to create a custom Authorize attribute to do the following: 我正在尝试创建自定义Authorize属性来执行以下操作:
This is when the user tries to open up the Search controller. 这是用户尝试打开搜索控制器时。 I made the custom Authorize attribute like this:
我做了这样的自定义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");
}
}
}
And this is my Search controller: 这是我的搜索控制器:
namespace WebApplication2.Controllers
{
[DenyRegularUser(Roles ="Regular user")]
public class SearchController : Controller
{
// GET: Search
public ActionResult Index()
{
return View();
}
}
}
But for some reason, even when I update the user's role from Regular user to Administrator or Subscriber, I get redirected to login page: /user/login... 但出于某种原因,即使我将用户的角色从普通用户更新为管理员或订阅者,我也会被重定向到登录页面:/ user / login ...
This shouldn't happen as the login functionality works perfectly and I get the role of the user... 这不应该发生,因为登录功能完美地工作,我得到了用户的角色......
What am I missing out here?? 我错过了什么?
This may help. 这可能有所帮助。
[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
}
}
I believe the IsAuthorized method is the correct way to override the AuthorizeAttribute. 我相信IsAuthorized方法是覆盖AuthorizeAttribute的正确方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.