== How to fix it in .NET

=== Code examples
The following code is vulnerable to XPath injections because untrusted data is
concatenated in an XPath query without prior validation.

==== Noncompliant code example

[source,csharp,diff-id=1,diff-type=noncompliant]
----
public class ExampleController : Controller
{
    [HttpGet]
    public IActionResult Authenticate(string user, string pass)
    {
        XmlDocument doc = new XmlDocument();
        
        String expression = "/users/user[@name='" + user + "' and @pass='" + pass + "']";

        return Json(doc.SelectSingleNode(expression) != null);
    }
}
----

==== Compliant solution

[source,csharp,diff-id=1,diff-type=compliant]
----
public class ExampleController : Controller
{
    [HttpGet]
    public IActionResult Authenticate(string user, string pass)
    {
        XmlDocument doc = new XmlDocument();
        if (!Regex.IsMatch(user, "^[a-zA-Z]+$") || !Regex.IsMatch(pass, "^[a-zA-Z]+$"))
        {
            return BadRequest();
        }

        String expression = "/users/user[@name='" + user + "' and @pass='" + pass + "']";

        return Json(doc.SelectSingleNode(expression) != null);
    }
}
----

=== How does this work?

As a rule of thumb, the best approach to protect against injections is to
systematically ensure that untrusted data cannot break out of the initially
intended logic.

include::../../common/fix/validation.adoc[]

In the example, a validation mechanism is applied to untrusted input to ensure
it is strictly composed of alphabetic characters.
