【发布时间】:2018-01-10 14:38:37
【问题描述】:
我的项目需要自定义身份验证,包括用户名、密码和自定义的第三个元素。
我已经编写了自定义代码来验证输入的详细信息并确定它们是否经过身份验证,但是当我绘制屏幕时,请求似乎没有被标记为经过身份验证。
_LoginPartial.cshtml
@using Microsoft.AspNet.Identity
@* this always evaluates to false - Why? *@
@if (Request.IsAuthenticated)
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@* stuff happens here *@
}
}
else
{
@* other stuff happens here *@
}
当我在调试中单步执行时,处理登录请求的控制器遵循预期的流程。相关方法是:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
CustomAuthenticator authenticator = new CustomAuthenticator(repository);
SignInStatus result = authenticator.Authenticate(model.CustomElement, model.UserName, model.Password);
if (result == SignInStatus.Success)
{
CustomIdentity ident = (CustomIdentity)authenticator.Principal.Identity;
HttpContext.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties { IsPersistent = true }, ident);
if (returnUrl == null)
{
return View();
}
else
return Redirect(returnUrl);
}
else
{
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
Authenticate() 方法执行检查(非身份)表以验证提供的凭据所需的操作。然后它创建自定义身份和主体。上面的 Login() 代码将此身份传递给 OwinContext AuthenticationManager。
以下是自定义 Principal 的部分内容:
public class CustomPrincipal : IPrincipal
{
public IIdentity Identity { get; set; }
public CustomPrincipal(CustomIdentity identity)
{
Identity = identity;
}
}
和身份:
public class CustomIdentity : ClaimsIdentity
{
public CustomIdentity(string authenticationType) : base(authenticationType) { }
public string CustomDetail { get; set; }
}
在 Startup.cs 中,我在 Configuration() 方法中有以下内容:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Login/Login"),
});
我已经完成了诸如 this 和 this 之类的身份教程以及其他一些教程,但均未成功。
我错过了什么?为什么我成功的身份验证过程没有将请求标记为已验证?
【问题讨论】:
-
你检查过this吗?
-
是的,@CamiloTerevinto。一个类似的问题,但是当他们调用提取的方法时,他们的问题就解决了。在我的情况下, app.UseCookieAuthentication() 调用正在发生,但仍然没有成功登录。谢谢。
标签: c# asp.net-mvc authentication owin