0

I have ValidateAntiForgeryToken attribute applied at class level. As shown in the below code.

[ValidateAntiForgeryToken, Authorize(Roles = "SuperUser")]
public class ManageController : BaseController
{
...
}

This class has several methods which accepts POST data and couple of methods which are exposed for GET operation. I would like to disable ValidateAntiForgeryToken for GET method without changing class level attribute. I know that I can do this by changing all the POST methods and applying ValidateAntiForgeryToken just to them. But I am hoping their is an easy way.

Just like the way Authorize attribute works along with AllowAnonymous where you can apply Authorize attribute at class level but then can change it method level by applying AllowAnonymous.

[Authorize]
public class AccountController : BaseController
{
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {            
            return View();
        }
}
ganders
  • 7,285
  • 17
  • 66
  • 114
ndd
  • 3,051
  • 4
  • 25
  • 40
  • look at this link http://stackoverflow.com/questions/5213345/how-can-i-set-the-validateantiforgerytoken-globally, basically you can create a filter, add the filter to the class and then the filter will add the ValidateAntiForgeryToken just to the post methods – Daniel Gpe Reyes Apr 13 '16 at 16:33

1 Answers1

0

I think this post will help you. http://prideparrot.com/blog/archive/2012/7/securing_all_forms_using_antiforgerytoken

By adding a custom IAuthorizationFilter you can skip checking GET

public class AntiForgeryAttribute: IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext authorizationContext)
    {
        if (authorizationContext.RequestContext.HttpContext.Request.HttpMethod != "POST")
            return;

        new ValidateAntiForgeryTokenAttribute().OnAuthorization(authorizationContext);
    }
}

Or later on in the article it explains how to create a custom attribute to skip validating some actions.

Sergio Robaudo
  • 101
  • 1
  • 6
  • Hi, welcome to stackoverflow. Please describe the answers more. when you have a link in your answer, it is probable that the page get removed and your answer get useless for other people in the future – Ashkan S Aug 12 '16 at 19:34
  • May be I am not following the article correctly and making mistake. I have uploaded code at https://www.dropbox.com/s/h5sbaoysbb0ayt7/AntifForgerySkip.zip?dl=0 could you please have a look? I also tried using a base class. – ndd Aug 15 '16 at 19:28