Saturday, May 2, 2015

Extend Authentication filter to handle redirect to Login in MVC

Form authentication has default mechanism to redirect to login page when user wants to access any data where authentication is needed. The setting is very simple within authentication element in config file.

<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>

So, it will automatically trigger to Login action within Account controller. That’s fine, but In need of we remove <forms> tag from authentication element? What will happen when user is not authorize to access a particular resource?

By default ASP.NET will search for login.aspx page in root directory in time of this situation. But If you follow MVC pattern then most probably you will not implement any login page in some .aspx file individually.

Probably you will call to Login action within Account controller, which will return Login page. Now, the question is how we can redirect to particular action in this situation ?
The solution is pretty simple, we will extend Autherization filter and within this we will implement our custom logic where we want to redirect when user is not authorize.

Here is implementation.

public class myAuthorization : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(new
                RouteValueDictionary(new { controller = "Account", action = "Login" }));
            }
           
       }
       
    }

So, we are redirecting to Account controller and Login action to handle not authenticated users.
Here is one secret controller which I have decorated with myAuthentication filter.

       [myAuthorization]
    public class ConfiController : Controller
    {
        public string cnfidential()
        {
            return "data";
        }

    }



No comments:

Post a Comment