Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net MVC Authorize attribute, redirect to custom "no rights" page

Asp.net MVC2 does redirect to login page with response 302 when authenticated user has no rights.

I would like to split into two actions

  1. If user is not authenticated then do what it does, redirect to login page.
  2. If user is authenticated but has no required rights then return appropriate http status code and show no rights dude page.

Is there any way to do it? Or am I doing something wrong with authorize and form authentication? Only way I can think of is by writing custom authorize attribute, which I want to avoid.

like image 941
mamu Avatar asked Dec 16 '10 04:12

mamu


3 Answers

You could write custom filter attribute like this:

public class CustomAuthorizeAttribute : ActionFilterAttribute     {         public override void OnActionExecuting(ActionExecutingContext filterContext)         {             if (filterContext.HttpContext.User.Identity == null || !filterContext.HttpContext.User.Identity.IsAuthenticated)             {                 filterContext.Result = new RedirectResult(System.Web.Security.FormsAuthentication.LoginUrl + "?returnUrl=" +                 filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.RawUrl));             }              //Check user right here             if (userNotRight)             {                 filterContext.HttpContext.Response.StatusCode = 302;                 filterContext.Result = new HttpUnauthorizedResult();             }         }     } 

And use it in controller:

[CustomAuthorize] public class HomeController : Controller {  } 
like image 56
hellangle Avatar answered Nov 07 '22 06:11

hellangle


You could write a custom authorize attribute and in the AuthorizeCore method if the user is not authenticated return a HttpUnauthorizedResult and if he is authenticated but not in roles perform some other action you would like. Note that if you return 401 status code the FormsAuthentication framework will eventually redirect with 302 to the login page.

like image 32
Darin Dimitrov Avatar answered Nov 07 '22 05:11

Darin Dimitrov


As suggested in Customizing authorization in ASP.NET MVC, you could subclass the AuthorizeAttribute to intercept the authenticated-but-unauthorized scenario and replace the result with a redirect.

like image 38
Brian Rogers Avatar answered Nov 07 '22 07:11

Brian Rogers