ASP.NET MVC redirect to an access denied page using a custom role provider

后端 未结 9 1969
忘了有多久
忘了有多久 2020-12-12 11:20

I\'m creating a custom role provider and I set a Authorize attribute specifying a role in my controller and it\'s working just fine, like this:

[Authorize(Ro         


        
相关标签:
9条回答
  • 2020-12-12 12:01
    public class AccessDeniedAuthorizeAttribute : AuthorizeAttribute
        {
            public override void OnAuthorization(AuthorizationContext filterContext)
            {
                base.OnAuthorization(filterContext);
    
                if (filterContext.Result is HttpUnauthorizedResult && WebSecurity.IsAuthenticated)
                {
                    filterContext.Result = new RedirectResult("~/Account/AccessDenied");
                }
            }
        }
    
    0 讨论(0)
  • 2020-12-12 12:03

    Take a look at tvanfosson's Answer from this very similar question, This is what I am doing(Thanks to tvanfosson), so now I just have to say:

    [MyAuthorize(Roles="SuperAdmin",ViewName="AccessDenied")]
    public class SuperAdminController : Controller
    ...
    

    If the user is not in the role, they will get thew view specified by ViewName.

    0 讨论(0)
  • 2020-12-12 12:04

    Just a small update to Vic Alcazar, Added details of the request url in redirect So that can log the details of the access denied and by who if want

    public class AccessDeniedAuthorizeAttribute : AuthorizeAttribute
    {
        public string AccessDeniedViewName { get; set; }
    
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
    
            if (filterContext.HttpContext.User.Identity.IsAuthenticated &&
                filterContext.Result is HttpUnauthorizedResult)
            {
                if (string.IsNullOrWhiteSpace(AccessDeniedViewName))
                    AccessDeniedViewName = "~/Account/AccessDenied";
    
                var requestUrl = filterContext.HttpContext.Request.Url;
    
                filterContext.Result = new RedirectResult(String.Format("{0}?RequestUrl={1}", AccessDeniedViewName, requestUrl));
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题