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.

39 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!

I needed an excel assignment homework help https://essaysprofessors.com/excel-homework-help-from-professors.html I read reviews of such companies on the Internet and choose right company. And I was not deceived.

Once you’ve found your perfect freelancer crm, most of the hard work is over. The next step is to familiarize yourself with this new business software tool, and set it up in a way that will help you accomplish important business objectives.A good CRM will help you automatically log and act on email conversations with clients and prospective clients.

Thanks that you share this protection. Now I'm very often use different programs and need this a lot. And now I will use my cheapest essay writing service for preparing for my classes.

추첨 방식은 로또와 비슷하나 확률은 그에 비해 극악인데 2012년 이전까지는 1~49 사이의 숫자 5개와 1~42 사이의 숫자 하나(이 숫자가 새겨진 볼 이름이 파워볼이다.)를 맞히면 1등을 할 수 있었으나 2012년 이후로는 1~69 사이의 숫자 5개, 1~26 사이의 파워볼 숫자 하나를 맞혀야 한다.

스웨디시 마사지는 여러 아시아 국가, 특히 한국에서 사용되는 고전적인 마사지 기술입니다. 앞서 언급한 많은 이론들은 마사지 부위에 더 많은 압력이 가해질수록 마사지가 더 효과적이라는 생각에 근거합니다. 또한 스웨디시 마사지에는 신체 이완, 통증 감소, 통증 감소, 혈류 개선, 순환 개선, 이완 개선, 근육 긴장 감소 등 여러 이점이 있습니다.

This absolutely an excellent erudition article blog, very inspiring and informative. check  fugashua jamb cut off mark

Our men genuine leather black bomber jacket is tighter-fitting, and less insulating than a coat, which is one of our best products only available at topcelebsjackets.com.

Woooooow!!
This is an interesting essay!
I would say that you did a really good job, and I appreciate and thank you for sharing it! oreo tv for pc

Thanks for providing this informative post.
I had a great time reading it because it was so well-written.
Also, look at Thoptv for pc

Post a Comment