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

前端 未结 5 1460
醉梦人生
醉梦人生 2021-01-31 09:08

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 us
5条回答
  •  孤街浪徒
    2021-01-31 09:31

    Similar to solutions suggested by @hellangle and @Andreas, I used the following code to solve this problem:

    public class CustomizedAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var userAuthInfo = GetUserAuthInfo();
    
            if (!userAuthInfo.IsAuthenticated())
            {
                filterContext.Result = new RedirectResult(UrlToYourLoginPage);
                return;
            }
    
            if (!userAuthInfo.IsAuthorized())
            {
                var result = new ViewResult {ViewName = "UnAuthorized"};
                result.ViewBag.Message = "Sorry! You are not authorized to do this!";
                filterContext.Result = result;
            }
        }
    }
    

    Of course, you need to implement the user authorization information class and related methods (GetUserAuthInfo, IsAuthenticated, IsAuthorized) according to your specific needs. Also a View named 'UnAuthorized' should be put to somewhere the MVC engine can find. Then it can be used on a controller class (pointed out in @hellangle's answer) or a action method:

    [CustomizedAuthorizeAttribute]
    public class TargetController : Controller
    {
        [CustomizedAuthorizeAttribute]
        public ActionResult TargetAction()
        {
            // Your Code
        }
    
    }
    

    In order to provide different access control strategy for various controller classes and action methods, implements a constructor for CustomizedAuthorizeAttribute class which accepts parameter(s) representing access control information and then Instantiate CustomizedAuthorizeAttribute class accordingly.

提交回复
热议问题