System.InvalidOperationException的未处理异常会破坏我的MVC应用程序?

时间:2015-06-10 19:26:33

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

我正在采用building a OWIN login from a empty MVC的概念,我刚开始使用我的数据库添加该部分,在创建一个Identity声明放入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()。我得到的例外是:

  

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

我是MVCs的新手,我不能告诉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);
    }
}

现在我明白了:

  

其他信息:类型为&#39; http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier&#39;未提供的ClaimsIdentity。

我更改了AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier; to AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;我不会再得到任何例外。这是正确的语法吗?

1 个答案:

答案 0 :(得分:1)

article可能有所帮助:

  

不幸的是,这个错误有点混乱,因为它说“nameidentifier或identityprovider”,即使你可能有两个中的一个。默认情况下,您需要两者。

     

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

protected void Application_Start()
{
    ...

    AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
}