【问题标题】:An unhandled exception of System.InvalidOperationException breaks my MVC App?System.InvalidOperationException 的未处理异常会破坏我的 MVC 应用程序?
【发布时间】:2015-08-26 05:57:06
【问题描述】:

我正在采用building a OWIN login from a empty MVC 的概念,并且在创建要放入 URL 的身份声明后,我刚刚开始添加使用我的数据库登录用户的部分。

这是我创建用户登录声明的代码

public class AuthenticationController : Controller
{
    IAuthenticationManager Authentication
    {
        get { return HttpContext.GetOwinContext().Authentication; }
    }

    [GET("Login")]
    public ActionResult Show()
    {
        return View();
    }

    [POST("Login")]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel input)
    {
        if (ModelState.IsValid)
        {
            if (input.HasValidUsernameAndPassword())
            {
                var identity = new ClaimsIdentity(new[] 
                {
                        new Claim(ClaimTypes.Name, input.Username),
                },
                DefaultAuthenticationTypes.ApplicationCookie,
                ClaimTypes.Name, ClaimTypes.Role);

                // if you want roles, just add as many as you want here (for loop maybe?)
                if (input.isAdministrator)
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, "Admins"));
                }
                else
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, "User"));
                }
                // tell OWIN the identity provider, optional
                // identity.AddClaim(new Claim(IdentityProvider, "Simplest Auth"));

                Authentication.SignIn(new AuthenticationProperties
                {
                    IsPersistent = input.RememberMe
                }, identity);

                return RedirectToAction("show", "authentication");
            }
        }
        return View("show", input);
    }

    [GET("logout")]
    public ActionResult Logout()
    {
        Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
        return RedirectToAction("Login");
    }
}

这是我的 Show.cshtml 代码

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Details</h4>
    <hr />
    @Html.ValidationSummary(true)

    <div class="form-group">
        @Html.LabelFor(model => model.Username, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Username)
            @Html.ValidationMessageFor(model => model.Username)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Password, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.RememberMe, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.RememberMe)
            @Html.ValidationMessageFor(model => model.RememberMe)
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Login" class="btn btn-default" />
        </div>
    </div>
</div>
}

这是我调用数据库并为登录用户存储数据的代码

public class LoginModel
{
    [Required]
    public string Username { get; set; }
    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    public bool RememberMe { get; set; }

    public bool isAdministrator { get; set; }

    public bool HasValidUsernameAndPassword()
    {
        bool result = false;
        int countChecker = 0;
        using (SqlConnection connection = new SqlConnection("server=server; database=db; user id=user; password=user"))
        {
            connection.Open();
            using (SqlCommand command = new SqlCommand("SELECT count(*) FROM ACCOUNTS WHERE active = 1 AND UserName = @param1 AND PasswordField = @param2", connection))
            {
                command.Parameters.Clear();
                command.Parameters.AddWithValue("@param1", Username);
                command.Parameters.AddWithValue("@param2", Password);
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        countChecker = Convert.ToInt32(reader[i].ToString());

                    }
                }
                if (countChecker > 0)
                {
                    result = true;
                    using (SqlConnection connect = new SqlConnection("server=server; database=db; user id=user; password=user"))
                    {
                        connect.Open();
                        using (SqlCommand com = new SqlCommand("SELECT Administrator FROM ACCOUNTS WHERE active = 1 AND UserName = @param1 AND PasswordField = @param2", connect))
                        {
                            com.Parameters.Clear();
                            com.Parameters.AddWithValue("@param1", Username);
                            com.Parameters.AddWithValue("@param2", Password);
                            SqlDataReader read = com.ExecuteReader();
                            while (read.Read())
                            {
                                for (int i = 0; i < read.FieldCount; i++)
                                {
                                    isAdministrator = Convert.ToBoolean(read[i].ToString());
                                }
                            }
                        }
                        connect.Dispose();
                        connect.Close();
                    }
                }
                else
                {
                    result = false;
                }
            }
            connection.Dispose();
            connection.Close();
        }
        return result;
    }
}

我的登录(LoginModel 输入)完成并返回到 Show.cshtml,然后这里有一个异常@Html.AntiForgeryToken()。我得到的例外是:

提供的 ClaimsIdentity 中不存在“http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier”或“http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider”类型的声明。要通过基于声明的身份验证启用防伪令牌支持,请验证配置的声明提供程序是否在其生成的 ClaimsIdentity 实例上提供这两个声明。如果配置的声明提供程序使用不同的声明类型作为唯一标识符,则可以通过设置静态属性 AntiForgeryConfig.UniqueClaimTypeIdentifier 进行配置。

我是使用 MVC 的新手,我不知道 ActionResult Login(LoginModel 输入)中缺少哪一个。有人可以向我解释一下我错过了哪一个。

我将 Corey 的建议添加到我的 Global.asax:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
        AttributeRoutingConfig.RegisterRoutes(RouteTable.Routes);
    }
}

现在我明白了:

附加信息:提供的 ClaimsIdentity 中不存在“http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier”类型的声明。

我更改了 AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;到 AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;而且我没有更多的例外。这是正确的语法吗?

【问题讨论】:

    标签: c# asp.net-mvc-5 antiforgerytoken


    【解决方案1】:

    这个article 可能会有所帮助:

    不幸的是,这个错误有点令人困惑,因为它显示“nameidentifier 或 identityprovider”,即使您可能有这两者之一。默认情况下你需要两者。

    无论如何,如果您没有使用 ACS 作为您的 STS,那么上述错误几乎可以告诉您解决问题所需的内容。您需要告诉 MVC 要使用哪个声明来唯一标识用户。为此,您可以设置 AntiForgeryConfig.UniqueClaimTypeIdentifier 属性(通常在 global.asax 的 App_Start 中)。例如(假设您想使用 nameidentifier 作为唯一声明):

    protected void Application_Start()
    {
        ...
    
        AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
    }
    

    【讨论】:

    • 附加信息:提供的 ClaimsIdentity 上不存在“schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier”类型的声明。将该行添加到我的代码后,我得到了这个。
    • 只是为了验证您在调试时是否通过了if (ModelState.IsValid)if (input.HasValidUsernameAndPassword())
    • 是的,我是。我刚刚根据您给出的答案更新了顶部的更改。
    猜你喜欢
    • 2014-10-10
    • 2020-04-12
    • 2019-11-05
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多