I'd like [Authorize] to redirect to loginUrl unless I'm also using a role, such as [Authorize (Roles="Admin")]. In that case, I want to simply display a page saying the user isn't authorized.
What should I do?
Here is the code from my modified implementation of AuthorizeAttribute; I named it SecurityAttribute. The only thing that I have changed is the OnAuthorization method, and I added an additional string property for the Url to redirect to an Unauthorized page:
// Set default Unauthorized Page Url here private string _notifyUrl = "/Error/Unauthorized"; public string NotifyUrl { get { return _notifyUrl; } set { _notifyUrl = value; } } public override void OnAuthorization(AuthorizationContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } if (AuthorizeCore(filterContext.HttpContext)) { HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache; cachePolicy.SetProxyMaxAge(new TimeSpan(0)); cachePolicy.AddValidationCallback(CacheValidateHandler, null); } /// This code added to support custom Unauthorized pages. else if (filterContext.HttpContext.User.Identity.IsAuthenticated) { if (NotifyUrl != null) filterContext.Result = new RedirectResult(NotifyUrl); else // Redirect to Login page. HandleUnauthorizedRequest(filterContext); } /// End of additional code else { // Redirect to Login page. HandleUnauthorizedRequest(filterContext); } } You call it the same way as the original AuthorizeAttribute, except that there is an additional property to override the Unauthorized Page Url:
// Use custom Unauthorized page: [Security (Roles="Admin, User", NotifyUrl="/UnauthorizedPage")] // Use default Unauthorized page: [Security (Roles="Admin, User")]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With