Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect [Authorize] to loginUrl only when Roles are not used?

Tags:

asp.net-mvc

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?

like image 218
royco Avatar asked Mar 24 '10 02:03

royco


1 Answers

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")] 
like image 182
Robert Harvey Avatar answered Sep 25 '22 06:09

Robert Harvey