在没有身份验证的情况下创建项目时的ASP.NET Identity Integration

时间:2016-06-24 15:46:50

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

我对Identity有一个问题,我对它不是很熟悉。不久前,我开始了一个新项目,原本并不打算附加任何身份验证。但是,随着项目的发展,我们发现我们应该实施它。由于最初没有这样设置,我创建了一个登录表单。

我找到了这个问题的答案并实施了它:

How to implement custom authentication in ASP.NET MVC 5

然而它不起作用,我不知道为什么。

这是我的代码:

没什么可看的,它只是一个简单的形式。

@{
    ViewBag.Title = "Login";
}

<div class="container">

<h2>Login</h2>

<br />

@using (Html.BeginForm("Login", "Main"))
{
    <div class="row">
        <div class="form-group col-xs-6">
            @Html.Label("Username", htmlAttributes: new { @class = "control-label col-sm-3" })
            <div class="col-sm-8">
                @Html.TextBox("username", null, new { @class = "form-control" })
                @*Html.ValidationMessageFor(model => model.EnrollmentOption, "", new { @class = "text-danger" })*@
            </div>
        </div>

        <div class="form-group col-xs-6">
        </div>

    </div>

    <div class="row">
        <div class="form-group col-xs-6">
            @Html.Label("Password", htmlAttributes: new { @class = "control-label col-sm-3" })
            <div class="col-sm-8">
                @Html.Password("password", null, new { @class = "form-control" })
                @*Html.ValidationMessageFor(model => model.EffectiveDate, "", new { @class = "text-danger" })*@
            </div>
        </div>

        <div class="form-group col-xs-6">
        </div>

    </div>

    <div class="row">
        <div class="form-group">
            <div class="col-md-offset-6 col-sm-5">
                <input type="submit" id="login" value="Sign in" class="btn btn-primary" />
            </div>
        </div>
    </div>
}

为此实施的行动就是这个,这更重要:

    [HttpPost]
    public ActionResult Login(string username, string password)
    {
        if (isLoginValid(username, password))
        {
            var ident = new ClaimsIdentity(
              new[] { 
          // adding following 2 claim just for supporting default antiforgery provider
          new Claim(ClaimTypes.NameIdentifier, username),
          new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),

          new Claim(ClaimTypes.Name,username),

          // No roles needed for now...
              },
              DefaultAuthenticationTypes.ApplicationCookie);

            HttpContext.GetOwinContext().Authentication.SignIn(
               new AuthenticationProperties { IsPersistent = false }, ident);
            return RedirectToAction("QuoteSearch"); // auth succeed 
        }
        else
        { 
            // invalid username or password
            ModelState.AddModelError("", "Invalid username or password");
            return View();
        }
    }

还有isLoginValid函数(现在它已设置为使用硬编码登录)

    [NonAction]
    private bool isLoginValid(string user, string password)
    {
        return (user.ToLower() == "someUser" && password.ToLower() == "myPassword");
    }

我不太了解声明或身份如何在其下工作。我确实确保添加所有必要的参考资料。在登录重定向后对我的操作使用authorize属性时,我收到来自IIS的未经授权的请求。我的代码有问题吗?

我应该更改或修复哪些内容才能使用Identity的授权部分?

谢谢,

2 个答案:

答案 0 :(得分:6)

经过一些故障排除后,感谢guyherman的评论,我找到了解决方案。由于我在没有认证的情况下创建了解决方案,因此删除了App_Start文件夹中的引用和必要的OWIN配置代码。

因此,尽管登录工作正常,但未定义Identity中的任何内容,也没有发生任何授权部分。通过创建一个新项目并添加所有需要的代码来配置Identity,我能够正确使用Authorize属性。没有任何问题。

(这个答案适用于ASP.NET 4.6,我想这对ASP.NET Core的处理方式不同)

更新:

为了使这个答案更好,我想我应该详细说明我做了什么才能使它发挥作用。

使用标识创建新项目时,如果您选择不添加,则会看到有多个文件未创建,您将需要这些文件,其中大部分都存储在App_Start中。

App_Start for a normal ASP.NET Project

我复制了我没有的文件,并更改了名称空间以匹配我的实际项目。一旦这样做,很明显我错过了哪些nuget包,所以我添加了我尚未添加的包。

Startup.Auth.cs将具有关键功能的定义,以使身份正常工作:

ConfigureAuth

必须在启动类中调用此函数。在配置方法中。

enter image description here

enter image description here

最后,要使一切工作,您还必须包含通常在Models文件夹中创建的文件IdentityModel.cs。在我的例子中,我将所有模型放在一个不同的项目中,因此我将该类放在那里并在IdentityConfig.cs上添加了引用,以便该类能够识别IdentityModel的存在。

enter image description here

就是这样。在我的情况下,我遇到很多身份问题尝试连接到数据库以寻找用户,因为身份没有配置数据库,我的应用程序由于数据库连接失败而开始崩溃。删除第三张图片中标有红色的线条使它对我有用。我不想要身份的数据库连接,因为我有自己的用户处理,这可能不是别人的情况。

答案 1 :(得分:1)

经过大量调试并感谢@Carlos的精心解答。如果您的项目是使用“无身份验证”创建的,则需要添加身份验证所需的缺少的Nuget包。

您需要安装以下

Microsoft.AspNet.Identity
Microsoft.AspNet.Identity.EntityFramework
Microsoft.AspNet.Identity.Owin
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Security