Search code examples
c#.netasp.net-mvcasp.net-identitymodelstate

Should I check authentication first or ModelState.IsValid


I have a .NET MVC5 website, where the user is logged in using Microsoft Identity. I have multiple form posts for adding and editing items across the site. I'm looking to know which order I should perform validation in:-

  • ModelState.IsValid and then User.Identity.IsAuthenticated
  • User.Identity.IsAuthenticated then ModelState.IsValid

I currently have the following code which works, but it seem to be a case of 'the chicken and egg':-

var user = UserAccountFunctions.GetUser(User);
if (user != null)
{
    ClientProfile profile = ClientProfile.GetUser(user.Id, db);

    if (profile != null)
    {
        if (ModelState.IsValid)
        {
            // Do logic here
        }
    }
}

Should I swap this code round to check the model first, before checking authentication so that I have:-

if (ModelState.IsValid)
{
    var user = UserAccountFunctions.GetUser(User);
    if (user != null)
    {
        ClientProfile profile = ClientProfile.GetUser(user.Id, db);

        if (profile != null)
        {

            // Do logic here...
        }
    }
}

Or is there simply no difference here? I repeat this code a lot throughout the site, so looking for which is the better option? I currently use the top one, because I feel that you shouldn't even attempt to check the model unless they are authenticated?

Any advice here?

Thanks!


Solution

  • Here is example of updating users's email:

                [AcceptVerbs(HttpVerbs.Post)]
                [Authorize]
                [ValidateAntiForgeryToken()]
                public ActionResult emailupdate(UserEmailEditModel editmodel_post)
                {   
                    if (!ModelState.IsValid)
                    {   
                      // redirect to email view and show errors
                    }
    
                    // check if posted id is the same as stored in session
                    if (User.Identity.GetUserId() != editmodel_post.user_id.ToString())
                    {
                       // redirect to email view and show errors
                    }
                }
    

    So

    1. Use Authorize attribute
    2. Use ValidateAntiForgeryToken attribute
    3. Check ModelState
    4. Check against session or database