संपादित करें

इसके माध्यम से साझा किया गया


CA3147: Mark verb handlers with ValidateAntiForgeryToken

Property Value
Rule ID CA3147
Title Mark verb handlers with ValidateAntiForgeryToken
Category Security
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 8 No

Cause

An ASP.NET MVC controller action method isn't marked with ValidateAntiForgeryTokenAttribute, or an attribute specifying the HTTP verb, such as HttpGetAttribute or AcceptVerbsAttribute.

Rule description

When designing an ASP.NET MVC controller, be mindful of cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET MVC controller. For more information, see XSRF/CSRF prevention in ASP.NET MVC and web pages.

This rule checks that ASP.NET MVC controller action methods either:

How to fix violations

When to suppress warnings

It's safe to suppress a warning from this rule if:

  • The ASP.NET MVC controller action has no harmful side effects.
  • The application validates the antiforgery token in a different way.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA3147
// The code that's violating the rule is on this line.
#pragma warning restore CA3147

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA3147.severity = none

For more information, see How to suppress code analysis warnings.

ValidateAntiForgeryToken attribute example

Violation:

namespace TestNamespace
{
    using System.Web.Mvc;

    public class TestController : Controller
    {
        public ActionResult TransferMoney(string toAccount, string amount)
        {
            // You don't want an attacker to specify to who and how much money to transfer.

            return null;
        }
    }
}

Solution:

using System;
using System.Xml;

namespace TestNamespace
{
    using System.Web.Mvc;

    public class TestController : Controller
    {
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult TransferMoney(string toAccount, string amount)
        {
            return null;
        }
    }
}

HttpGet attribute example

Violation:

namespace TestNamespace
{
    using System.Web.Mvc;

    public class TestController : Controller
    {
        public ActionResult Help(int topicId)
        {
            // This Help method is an example of a read-only operation with no harmful side effects.
            return null;
        }
    }
}

Solution:

namespace TestNamespace
{
    using System.Web.Mvc;

    public class TestController : Controller
    {
        [HttpGet]
        public ActionResult Help(int topicId)
        {
            return null;
        }
    }
}