Skip to content

Instantly share code, notes, and snippets.

@tathamoddie
Created April 25, 2012 07:36
Show Gist options
  • Save tathamoddie/2487786 to your computer and use it in GitHub Desktop.
Save tathamoddie/2487786 to your computer and use it in GitHub Desktop.
[TestFixture]
public class AntiForgeryTests
{
[Test]
[TestCaseSource(typeof(AllMvcActions), "GetActions")]
public void AllPostActionsShouldHaveAntiForgeryValidation(MethodInfo action)
{
if (!action.GetCustomAttributes(typeof (HttpPostAttribute), false).Any())
return;
if (action.GetCustomAttributes(typeof (ValidateAntiForgeryTokenAttribute), false).Any())
return;
if (action.DeclaringType == null)
throw new InvalidOperationException("An assumption about reflection was just proven wrong: action.DeclaringType was null. Test failed (method may or may not actually be correct).");
Assert.Fail("{0}.{1} is marked with [HttpPost] but missing [ValidateAntiForgeryToken]", action.DeclaringType.Name, action.Name);
}
public class AllMvcActions
{
public IEnumerable<MethodInfo> GetActions()
{
var controllers = typeof(MvcApplication)
.Assembly
.GetTypes()
.Where(t => typeof(Controller).IsAssignableFrom(t));
var actions = controllers
.SelectMany(c => c.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly))
.Where(m => !m.IsSpecialName);
return actions;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment