Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net MVC antiforgerytoken on exception RedirectToAction

I have implimented the AnitforgeryToken with my asp.net MVC forms, and also added the attribute to my login procedure, however when the check failes i wish to redirect to my fraud action rather than an exception page. is this possible within the attribute ????

thanks

like image 945
davethecoder Avatar asked Nov 07 '09 12:11

davethecoder


2 Answers

In case you do not want to put [HandleError] attribute on all actions that have [ValidateAntiForgeryToken], you may add a custom filter to your Global filters:

in Global.asax under Application_Start():

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

and then:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new AntiForgeryTokenFilter());
    }
}

AntiForgeryTokenFilter.cs:

public class AntiForgeryTokenFilter : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if(filterContext.Exception.GetType() == typeof(HttpAntiForgeryException))
        {
            filterContext.Result = new RedirectResult("/"); // whatever the url that you want to redirect to
            filterContext.ExceptionHandled = true;
        }
    }
}
like image 55
Dmitry Efimenko Avatar answered Nov 16 '22 04:11

Dmitry Efimenko


The ValidateAntiForgeryTokenAttribute will just throw HttpAntiForgeryException. You could use the HandleErrorAttribute to handle this scenario:

[HandleError(
    ExceptionType = typeof(HttpAntiForgeryException), 
    View = "Unauthorized")]
[ValidateAntiForgeryToken]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SomeActionThatRequiresToken() 
{
    return View();
}
like image 13
Darin Dimitrov Avatar answered Nov 16 '22 04:11

Darin Dimitrov