How to use properly IAuthorizationFilter in an MVS solution to check a permission and redirect

1k Views Asked by At

I am trying out the following scenario in ASP.NET MVC. I want to built a simple MVC application where I want to create a custom IAuthorizationFilter which should only execute an SQL Statement to check if user exists. If user exists then go on otherwise redirect to a different view.

I created a new class for the custom filter:

public class CustomAuthorizationAttribute : FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        filterContext.Controller.ViewBag.AutherizationMessage = "Custom Authorization: Message from OnAuthorization method.";
    }
}

In the action where I wanted to check for the user I added the filter:

    [CustomAuthorizationAttribute]
    public ActionResult Index()
    {
        ViewBag.Title = "Home Page";

        return View();
    }

In the view, I added the output value:

<div>
    @ViewBag.AutherizationMessage
</div>

In general when I execute the solution and execute the action I receive the message on the website as expected.

But know I a real world scenario, how and where to implement the check and how to redirect on Not Authorized?

1

There are 1 best solutions below

0
Praveen Maurya On

1.Create your custom Authorize attribute as mentioned below: 2.Create an action in your controller handling invalid user (like Restricted action in home Controller in below example , this action simply return a view)

public class CustomAuthorize : AuthorizeAttribute
    {


        protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAuthenticated)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "Restricted" }));// Create an Action name "Restricted" in your home controller or call whatever action you need to call.
            }
            else
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var authorized = base.AuthorizeCore(httpContext);


            if (!authorized)
            {
                // The user is not authenticated
                return false;
            }
            string user = HttpContext.Current.User.Identity.Name;

            bool isUser = IsAppUser(user);

            return isUser;

        }

        private bool IsAppUser(string user)
        {

           //Check existence of your user and return true or false as per the condition

        }



    }

Now user this custom Authorize attribute in your action wherever you need. hope this help you :)