ModelState.IsValid should be checked in controller actions

Greetings,

I am wondering if anyone can shed some light on the matter of ModelState validation flags that SonarCloud would mark our backend (no-direct-frontend ties, API service kinda scenarios) functions.

In our code, we have lots of API-style calls and functions that get flag for no ModelState.IsValid validation but we have our own validation.

Scenario Example (Razor Controller Code):

    public IActionResult InitiateOAuth2Login(string email)
    {
        if (string.IsNullOrEmpty(email) 
            || email.Length > 100 
            || !email.Contains("@") 
            || email.Contains(";") 
            || email.Contains(":")) return Redirect("/Error");
    
    ..... <rest-of-login-code>

We tried the built in validation methods prescribed but as this is a backend function there is no frontend validation that ModelState.IsValid will work against…

We did something like:

    public IActionResult InitiateOAuth2Logout(LogoutModel LOM)
    {
        var validationResults = new List<ValidationResult>();
        var validationContext = new ValidationContext(LOM, null, null);
        bool isValid = Validator.TryValidateObject(LOM, validationContext, validationResults, true);

..... <rest-of-logout-code>

With supporting Model class:

public class LogoutModel
{
    [Required(ErrorMessage = "Email is required.")]
    [EmailAddress(ErrorMessage = "Invalid email address format.")]
    public string email { get; set; }
}

This of course like the login example above works in practice to validate the email variable… but gets flagged by SonarCloud as not handled…

Are we in error and in need of a push in a proper direction or is this something that we need to keep in the “Responsibility” catogory so to speak and just do duedeligence manually to keep things safe?

Thanks lots.

Oh… the usual flag on the functions:

Hi @Kirk.
The way you decorated LogoutModel with validation attributes seems correct to me.
In InitiateOAuth2Logout all you have to do is check the ModelState.IsValid property at the beginning of the method:

public IActionResult InitiateOAuth2Logout(LogoutModel LOM)
{
   if (!ModelState.IsValid)
   {
      // handle the error, e.g. return BadRequest()
   }
   // the rest of Logout functionality...
}

If you want to use custom validation then it’s recommended that you turn off the rule for that particular method or class.

There’s one section I don’t understand:

We tried the built in validation methods prescribed but as this is a backend function there is no frontend validation that ModelState.IsValid will work against…

Can you elaborate? AFAIK there’s no need for a frontend component for validation using ModelState.IsValid.