【问题标题】:Should I check authentication first or ModelState.IsValid我应该先检查身份验证还是 ModelState.IsValid
【发布时间】:2017-07-18 00:59:51
【问题描述】:

我有一个 .NET MVC5 网站,用户使用 Microsoft 身份登录。我有多个表单帖子用于在整个站点中添加和编辑项目。我想知道我应该按哪个顺序执行验证:-

  • ModelState.IsValid 然后是 User.Identity.IsAuthenticated
  • User.Identity.IsAuthenticated 然后 ModelState.IsValid

我目前有以下代码有效,但它似乎是“鸡和蛋”的情况:-

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

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

在检查身份验证之前,我是否应该先交换此代码以检查模型,以便我拥有:-

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

        if (profile != null)
        {

            // Do logic here...
        }
    }
}

或者这里根本没有区别?我在整个网站上多次重复此代码,所以寻找更好的选择?我目前使用最上面的那个,因为我觉得除非经过身份验证,否则您甚至不应该尝试检查模型?

这里有什么建议吗?

谢谢!

【问题讨论】:

  • 首先进行身份验证,然后将[Authorize] 属性添加到您的方法(或控制器)
  • 使用授权属性,就像斯蒂芬所说的那样。验证在授权后进行,因为您不希望授权用户查看模型是否无效
  • [Authorize] 和 if(User.Identity.IsAuthenticated) 一样吗?如果是这样,那就太好了!

标签: c# .net asp.net-mvc asp.net-identity modelstate


【解决方案1】:

以下是更新用户电子邮件的示例:

            [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
                }
            }

所以

  1. 使用授权属性
  2. 使用ValidateAntiForgeryToken属性
  3. 检查 ModelState
  4. 检查会话或数据库

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 2018-12-23
    • 2019-08-23
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    相关资源
    最近更新 更多