c# - 在没有身份验证的情况下创建项目时的 ASP.NET 身份集成

标签 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>
}

为它执行的 Action 是这个,这个更重要:

    [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");
    }

我不太了解 claims 或 Identity 在底层是如何工作的。不过,我确实确保添加了所有必要的引用资料。在登录重定向后对我的操作使用授权属性时,我从 IIS 收到未经授权的请求。我的代码有问题吗?

我应该更改或修复什么才能使用身份的授权部分?

谢谢,

最佳答案

经过一些故障排除并感谢 guysherman 的评论,我找到了解决方案。由于我在创建解决方案时没有考虑身份验证,因此我删除了 App_Start 文件夹中的引用和必要的 OWIN 配置代码。

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

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

更新:

为了更好地回答这个问题,我想我应该详细说明我做了什么来让它发挥作用。

当创建一个带有标识的新项目时,如果您选择不添加它,您会看到有几个文件不会被创建,您将需要这些文件,其中大部分存储在 App_Start 中。

App_Start for a normal ASP.NET Project

我复制了我没有的文件并更改了 namespace 以匹配我的实际项目。一旦这样做,我就会清楚我缺少哪些 nuget 包,所以我添加了那些我还没有添加的包。

Startup.Auth.cs 将定义用于身份验证的关键函数:

配置认证

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

enter image description here

enter image description here

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

enter image description here

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

关于c# - 在没有身份验证的情况下创建项目时的 ASP.NET 身份集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38017311/

相关文章:

c# - DataTable.Compute 计算十进制表达式时失败

asp.net-mvc - 模型内部属性的自定义模型绑定(bind)器

ASP.NET MVC - RequireHttps - 指定重定向 URL

Spring 和条纹安全设计

c# - 如何根据特定条件使用滑动窗口触发 RX 信号

c# - 使用 Math.NET C# 计算导数

asp.net-mvc - asp.net mvc web api项目中的MessageHandlers vs Filters

mysql - 仅使用 AWS Cognito + mysql

macos - 如何强制 git 提示输入凭据?

c# - 为什么绑定(bind)不足以刷新 WP7 (MVVM) 中的 UI