我对身份有疑问,而且我对此不太熟悉。不久前,我开始了一个新项目,最初并不打算附加任何身份验证。然而,随着项目的发展,我们发现我们应该实施它。由于最初并不是这样设置的,所以我创建了一个登录表单。
我找到了这个问题的答案并实现了它:
如何在 ASP.NET MVC 5 中实现自定义身份验证 https://stackoverflow.com/questions/31584506/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");
}
我不太了解声明或身份在底层是如何运作的。不过,我确实确保添加了所有必要的参考资料。在登录重定向后对我的操作使用授权属性时,我收到来自 IIS 的未经授权的请求。我的代码有问题吗?
我应该更改或修复哪些内容才能使用身份的授权部分?
Thanks,