我正在WebApi,asp.net身份和OWIN中实现2因素身份验证。每次登录时,我都会获得SignInStatus =成功永远不会达到SignInStatus = RequiresVerification,尽管已启用用户TwoFactorAuthentication。
以下是一些代码段, Startup.cs:
private void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
app.UseOAuthBearerTokens(OAuthOptions);
}
Action method for enabling two factor authentication,
[HttpPost]
public async Task<IHttpActionResult> EnableTwoFactorAuthentication()
{
var user = await this.AppUserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
IdentityResult result = await this.AppUserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true);
await this.AppSignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
}
return Ok();
}
请提出解决方案。
答案 0 :(得分:0)
如果您被困在这里,解决问题的一种方法是将SignInManager中的方法直接复制到您的代码中,然后调用它们,以便您逐步遍历这些方法并查看为什么状态错误。对我来说,问题最终是我实例化了UserManager
:
new MyUserManager()
代替正确的方法:
HttpContext.GetOwinContext().Get<MyUserManager>()
我使用它作为模板进行设置: https://github.com/adamtuliper/ASP.NET-Identity-Samples/tree/master/BasicTemplate%20-%20Two%20Factor/BasicTemplate
答案 1 :(得分:0)
SignInManager 返回 RequiresVerification 如果:
dbo.ASpnetUsers 已将用户设置为 true TwoFactorEnabled 和 EmailConfirmed 并且应确认用户电子邮件,电子邮件不能为空或为空。
var result = SignInManager.PasswordSignIn(usernameIdentity, model.Password, model.RememberMe, shouldLockout: true);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", returnUrl);
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid username or password.");
return View(model);
}