Protecting against CSRF attacks in ASP.Net MVC

CSRF attacks are one of the many security issues that web developers must defend against.  Fortunately, ASP.Net MVC makes it easy to defend against CSRF attacks.  Simply slap on [ValidateAntiForgeryToken] to every POST action and include @Html.AntiForgeryToken() in every form, and your forms will be secure against CSRF.

However, it is easy to forget to apply [ValidateAntiForgeryToken] to every action.  To prevent such mistakes, you can create a unit test that loops through all of your controller actions and makes sure that every [HttpPost] action also has [ValidateAntiForgeryToken]. 

Since there may be some POST actions that should not be protected against CSRF, you’ll probably also want a marker attribute to tell the test to ignore some actions.

This can be implemented like this:

First, define the marker attribute in the MVC web project.  This attribute can be applied to a single action, or to a controller to allow every action in the controller.

///<summary>Indicates that an action or controller deliberately 
/// allows CSRF attacks.</summary>
///<remarks>All [HttpPost] actions must have 
/// [ValidateAntiForgeryToken]; any deliberately unprotected 
/// actions must be marked with this attribute.
/// This rule is enforced by a unit test.</remarks>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class AllowCsrfAttacksAttribute : Attribute { }

Then, add the following unit test:

[TestMethod]
public void CheckForCsrfProtection() {
    var controllers = typeof(MvcApplication).Assembly.GetTypes().Where(typeof(IController).IsAssignableFrom);
    foreach (var type in controllers.Where(t => !t.IsDefined(typeof(AllowCsrfAttacksAttribute), true))) {
        var postActions = type.GetMethods()
                                .Where(m => !m.ContainsGenericParameters)
                                .Where(m => !m.IsDefined(typeof(ChildActionOnlyAttribute), true))
                                .Where(m => !m.IsDefined(typeof(NonActionAttribute), true))
                                .Where(m => !m.GetParameters().Any(p => p.IsOut || p.ParameterType.IsByRef))
                                .Where(m => m.IsDefined(typeof(HttpPostAttribute), true));

        foreach (var action in postActions) {
            //CSRF XOR AntiForgery
            Assert.IsTrue(action.IsDefined(typeof(AllowCsrfAttacksAttribute), true) != action.IsDefined(typeof(ValidateAntiForgeryTokenAttribute), true),
                            action.Name + " is [HttpPost] but not [ValidateAntiForgeryToken]");
        }
    }
}
typeof(MvcApplication) must be any type in the assembly that contains your controllers.  If your controllers are defined in multiple assemblies, you’ll need to include those assemblies too.

29 comments:

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

I know that advices from https://essaydragon.com/blog/spend-the-entire-summer-holidays-on-campus will be useful for students. You can read more about living on campus there.

The above article is nice and interesting, thank you willing to share! Greetings success of admin Percetakan Murah Rawamangun Jakarta Timur wish you deign to visit my website, thank you :)

TreasureBox is operated by a group of young, passionate, and ambitious people that are working diligently towards the same goal - make your every dollar count, as we believe you deserve something better.
Check out the best
bedroom furniture nz
pregnancy pillow nz
chicken coops nz

Cross-site demand fraud, otherwise called a single tick assault or session riding and truncated as ... CSRF vulnerabilities have been known and now and again abused https://www.assignmentspot.co.uk/ since ... A cross-webpage demand fraud is a confounded representative assault against a web ... such activities should change to HTTP POST or utilize hostile to CSRF insurance.

I am glad that I saw this post. It is informative blog for us and we need this type of blog thanks for share this blog, Keep posting such instructional blogs and I am looking forward for your future posts.
Cyber Security Projects for Final Year

JavaScript Training in Chennai

Project Centers in Chennai

JavaScript Training in Chennai

Delighted in perusing the article above, truly clarifies everything in detail, the article is fascinating and viable. Much thanks to you and waiting for your upcoming articles - Real Love

This article has suggested to me many new ideas. I will embark on doing it. Hope you can continue to contribute your talents in this area. Thank you
install thunder

Among other courses, healthcare essay writing help online has become popular since students seek Healthcare Assignment Writing Services and healthcare research research paper writing services.

Developers, programmers and programming scholars face this problem multiple time in their career. Thanks for sharing solution for CSRF attacks in easier way.Student can seek Paper help online to solve their programming problems.

the globe are well trained in their chosen field of study. Homework Assignment Help which reflects in multiple offer. It is important to choose the best one among the many.

When creating an online dissertation writing service, I initially pursued the goal of helping students with completing tasks that were difficult for them, and I succeeded. Now our team helps a lot.

The effect of a fruitful CSRF assault is restricted to the capacities uncovered by the weak application and advantages of the client. For instance, this assault could bring about an exchange of assets, changing a secret key. balloon in a box

the globe are well trained in their chosen field of study. order custom assignment which reflects in multiple offer. It is important to choose the best one among the many.

Acquire the protection against the fake law assignment writing service UK writers, and always use the authentic agency.

Your blog is helpful to me thanks for this helpful blog. Its very interesting to read and easy to understand. Thanks for sharing. To Change Roadrunner Email Password please contact our technical expert for instant help.

Since there may be some POST actions that should not be protected against CSRF, you’ll probably also want a marker attribute to tell the test to ignore some actions. cheap wedding bands germany , cheap wedding bands usa ,

Since there might be some POST activities that ought not be secured against CSRF, you'll likely likewise need a marker quality to advise the test to overlook a few activities. Expert Essay Writer at Wewriteessay.co.uk

MVC is a design pattern that separates the user interface (view), the data (model), and the application logic (controller) in a web application. Requests are sent to a Controller in the MVC pattern for Coursework Help UK websites, which is responsible for dealing with the Model to conduct actions and/or retrieve data.

you can make unit test. do my assignment paper that circles through the entirety of your regulator activities and ensures that each.

If you are looking for a solution to relax then Jigsaw Puzzles will be the best choice today! This is a website with hundreds of games to satisfy your passion, and will satisfy the most demanding players!

Post a Comment